Search⌘ K

Solution Review: Remove Duplicates From an ArrayList

Explore how to remove duplicate elements from an ArrayList by using nested loops and the remove method. This lesson helps you understand practical techniques for managing Java collections effectively.

We'll cover the following...

Solution

Java
class DuplicatesRemover {
public static void removeDuplicates(ArrayList < Character > arrList) {
for (int i = 0; i < arrList.size(); i++) {
for (int j = i + 1; j < arrList.size(); j++) {
if (arrList.get(i).equals(arrList.get(j))) { //check if there is any duplicate
arrList.remove(j); //remove duplicate
j--; // j is decremented
}
}
}
}
public static void main( String args[] ) {
ArrayList<Character> input = new ArrayList<Character>(Arrays.asList('d', 'c','a', 'b', 'b', 'c', 'c', 'c', 'd'));
System.out.println("Array List before calling removeDuplicates");
for (int i = 0; i < input.size(); i++){
System.out.print(input.get(i)+ " ");
}
System.out.println();
removeDuplicates(input);
System.out.println("Array List after calling removeDuplicates");
for (int i = 0; i < input.size(); i++){
System.out.print(input.get(i)+ " ");
}
System.out.println();
}
}

How does the above code work?

  • In the above solution code, we ...