Skip to content

Java ArrayList get unique values example

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

How to get unique values from ArrayList in Java (unique elements)?

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 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, the 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 the 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 the addition of duplicate elements to the ArrayList?

How about preventing the addition of 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, the element “one” was not added the second time.

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

This example is a part of the Java ArrayList tutorial with examples.

Please let me know your views in the comments section.

About the author

Leave a Reply

Your email address will not be published.