Collections

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.

Example

Output

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.

Output

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.

Output

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.

Output

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.

Join 1000+ fellow learners! Enter your email address below: