Collections

Remove duplicates from ArrayList in Java example

Remove duplicates from ArrayList in Java example shows how to remove duplicate elements from ArrayList in Java. Example also shows how to remove duplicate elements from ArrayList using Java 8 stream.

How to remove duplicates from ArrayList in Java?

In some situations, you do not want duplicate elements in the ArrayList object. You can remove duplicate elements from ArrayList using below given ways.

1) Remove duplicates from ArrayList using LinkedHashSet

Set collection does not allow duplicate elements, you can use this property to remove duplicate elements from ArrayList as given below.

Output

We first created LinkedHashSet containing all the elements of an ArrayList using LinkedHashSet constructor. Since, Set does not allow duplicates, it automatically added only elements which are unique. After that, we deleted all the existing elements from the ArrayList using clear method. Once the ArrayList is empty, we added back all the unique elements stored in the LinkedHashSet back to the ArrayList using addAll method.

Note: You can also use HashSet instead of LinkedHashSet. But since ArrayList is an ordered collection, we used LinkedHashSet to retain the order of the elements. If you use HashSet, there will be no guarantee of the order of the elements of the ArrayList after removing duplicates. If order of the elements is important to you, use LinkedHashSet.

2) Remove duplicates from ArrayList using Java 8 stream, Collectors

If you are using Java 8, removing duplicates from ArrayList is just one line of code as given below.

Output

Important Note: If the ArrayList contains objects of the custom class, you need to implement equals and hashcode methods in your class in order for the above approaches to work.

Please let us know your views in the comments section below.

 

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.