Remove Duplicates from ArrayList

ArrayList implements List Interface and hence, allows duplicates.

1. The simplest approach to remove repeated objects from ArrayList is to copy them to a Set e.g. HashSet and then copy it back to ArrayList. This will remove all duplicates without writing any more code.
2. If original order of elements in ArrayList is important for you, as List maintains insertion order, you should use LinkedHashSet because HashSet doesn't provide any ordering guarantee.
3. Iterate over the ArrayList to check for duplicate and remove() it.

Please Note- If you are using deleting duplicates while iterating, make sure you use Iterator's remove() method and not the ArrayList one to avoid ConcurrentModificationException.  In this tutorial we will see this approach to remove duplicates.

Also, If you don't prefer converting List to Set than you can still go with copying data from one ArrayList to other ArrayList and removing duplicates by checking with ArrayList.contains() method.

Comments

Popular posts from this blog

@Overrride annotation introduced in Java1.5

Liskov Substitution Principle (LSP)

Marie Choco Lava