Java Sort HashSet Example

This example shows how to sort a HashSet in Java. This example also shows sorting a Java HashSet of custom class objects using a TreeSet and a Comparator object.

How to sort HashSet in Java?

The HashSet class in Java is a Set implementation that is backed by a HashMap instance. Just like the HashMap, the HashSet class does not make any guarantee to maintain the order of its elements. The order of the elements returned by its Iterator may not stay constant over time.

Sorting the HashSet elements does not make sense because it may not be returned in the sorted order by the HashSet iterator even after sorting it. If you want the Set functionality but still want the elements to be sorted, you can convert the HashSet to a TreeSet using the below given TreeSet constructor.

This constructor creates a new TreeSet object containing all the elements of the specified collection, sorted according to the natural order.

Output

As we can see from the output, all the HashSet elements are automatically sorted in the TreeSet object.

How to sort HashSet of custom class objects?

In the above example, we used the HashSet of Integer type. Let’s try with a custom class object this time.

Output

The elements inserted into TreeSet either must implement the Comparable interface or a custom Comparator must be provided at the TreeSet creation time using the constructor. We did neither of that in our Subject custom class and hence the java.lang.ClassCastException was thrown.

In order to solve this exception, we can either implement the Comparable interface in the Subject class or we can provide a custom Comparator in the TreeSet constructor. I am going to show how to sort HashSet using the Comparator below.

Output

As we can see from the output, the HashSet of custom class objects is now sorted according to the order defined by the Comparator object.

This example is a part of the HashSet in Java Tutorial with Examples.

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

References:
Java 8 HashSet

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

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

Online Shopping