How to Remove Duplicate Elements From ArrayList in Java

This post shows different ways to remove duplicate elements from ArrayList in Java.
ArrayList in Java is designed to store repeated elements where as HashSet only store unique elements, using that feature of HashSet in Java you can remove duplicates from ArrayList.
Only problem is HashSet is an unordered collection so insertion order won’t be maintained in HashSet. If you want insertion order of the List to be maintained then you can use LinkedHashSet for removing duplicates from ArrayList. LinkedHashSet in Java maintains the insertion order. Let’s see code examples using both of these collections.

Removing duplicate elements from ArrayList using HashSet

Output

As you can see from the output duplicates are removed from the List but insertion order is not maintained. That brings us to the next program using LinkedHashSet to remove duplicate elements.

Removing duplicate elements from ArrayList using LinkedHashSet

Output

As you can see from the output duplicates are removed from the List and insertion order is maintained too.

Removing duplicate elements from ArrayList using Stream API

Java 8 onwards you can use Stream API to remove duplicates from a List. In Stream API there is a distinct() method that returns a stream consisting of the distinct elements of this stream.

Output

As you can see duplicates are removed from the ArrayList and insertion order is also maintained.

That’s all for the topic How to Remove Duplicate Elements From ArrayList in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.