Skip to content

Remove duplicates from ArrayList in Java example

Remove duplicates from ArrayList in Java example shows how to remove duplicate elements from ArrayList in Java using LinkedHashSet and 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) Using LinkedHashSet class

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

Output

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

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

2) Using Java 8 stream and 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 the equals and hashcode methods in your class in order for the above approaches to work.

This example is a part of the ArrayList in Java tutorial.

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

About the author

Leave a Reply

Your email address will not be published.