Java ArrayList get unique values example

Java ArrayList get unique values example shows how to get unique values from ArrayList in Java. Example also shows how to maintain insertion order of the elements.

How to get unique values from ArrayList in Java?

ArrayList class does not prevent us from adding duplicate values. If you want to get unique values from the ArrayList, you can convert the ArrayList to HashSet which does not allow the duplicate values.

Use constructor of HashSet class which accepts Collection as an argument to convert ArrayList to HashSet.

This constructor accepts any collection and creates a new set containing the elements of the specified collection.



How to maintain insertion order while getting unique values from ArrayList?

As you may have observed from the output, order of the elements retrieved from HashSet is not the same order in which we added elements to the ArrayList. That is because HashSet does not maintain insertion order of the elements.

If you want to maintain the insertion order of the elements, you can use LinkedHashSet instead of HashSet. LinkedHashSet maintains the order in which the elements are inserted while retrieving.


How to get unique values from ArrayList using Java 8?

If you are using Java version 8, you can use stream and distinct to get unique values from the ArrayList in just one line as given below.


How to prevent addition of duplicate elements to the ArrayList?

How about preventing addition of the duplicate elements to the ArrayList in the first place? If you want to add only unique elements to the ArrayList, you should first check if the element already exists in the ArrayList. If the element exists then do not add it, otherwise add it. Use contains method of ArrayList to check whether the element exists in the ArrayList.


As you can see from the output, element “one” was not added second time.

Note : contains method of ArrayList class internally uses equals method of argument object to compare them with one another. Since String class has implemented equals method, above example worked and it identified the duplicate “one” object. If your ArrayList contains objects of custom class, then that class must implement equals and hashCode methods to work.

Please let us know your views in the comments section.

About the author



rahimv has over 15 years of experience in designing and developing Java applications. His areas of expertise are J2EE and eCommerce. If you like the website, follow him on Facebook, Twitter or Google Plus.

Add Comment

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