Search⌘ K

Solution Review: Removing Duplicates From an ArrayList

Explore how to remove duplicate elements from an ArrayList in Java by using nested loops to compare and delete duplicates. This lesson helps you understand how to write a function, navigate loop indexes carefully, and modify the list while iterating to handle duplicates correctly.

Rubric criteria

Solution

Java
import java.util.ArrayList;
class Duplicates
{
public static void main(String args[])
{
ArrayList<String> colours = new ArrayList<String>();
// Adding the values
colours.add("blue");
colours.add("blue");
colours.add("red");
colours.add("yellow");
colours.add("green");
colours.add("red");
colours.add("red");
colours.add("green");
colours.add("blue");
// Calling the function removeDuplicates
removeDuplicates(colours);
System.out.println(colours);
}
// Implementing removeDuplicates function
public static void removeDuplicates(ArrayList<String> colours)
{
for(int i = 0; i < colours.size()-1; i++)
{
for(int j = i+1; j< colours.size(); j++)
{
if(colours.get(i).equals(colours.get(j))) // If duplicate found
{
colours.remove(j); // Removing duplicate
j--; // Moving one step back
}
}
}
}
}

Rubric-wise explanation


Point 1:

Look at line 26. We create the header of the function removeDuplicates().

Point 2, 3:

Next, we create an outer for loop. We pick a color one by one and ...