Skip to content

Convert HashSet to TreeSet in Java Example

This example shows how to convert HashSet to TreeSet in Java. This example also shows how to convert HashSet to TreeSet using the constructor and addAll method.

How to convert HashSet to TreeSet in Java?

The HashSet and TreeSet classes are implementations of the Set interface. The HashSet is backed by an instance of the HashMap class, while the TreeSet is an implementation based on the TreeMap.

Since both the classes implement the Set interface, none of them allow duplicate elements. The HashSet class does not guarantee the order of its elements while TreeSet class sorts the elements according to their natural order or by the provided custom comparator.

There are a couple of ways using which we can convert HashSet object to the TreeSet object as given below.

1. Using TreeSet constructor

The TreeSet class provides a copy constructor that creates a new TreeSet object containing all the elements of the specified collection object.

Since the HashSet class is a child class of the Collection interface, we can pass the HashSet object into this constructor.

Output

As we can see from the output, the TreeSet class has automatically sorted the elements in their natural order i.e. ascending order for the Integer type.

2. Using the addAll method of the TreeSet class

The addAll method of the TreeSet class adds all the elements of the specified collection to this set object.

We will first create a new and empty TreeSet object and then use the addAll method to add all elements of the HashSet object to the TreeSet object as given below.

Output

How to convert HashSet of the custom class objects to a TreeSet object?

Let’s have a look at the below example of HashSet of custom class elements.

Output

The code throws the java.lang.ClassCastException exception because all elements of the TreeSet either must implement the Comparable interface or a custom Comparator must be provided in the TreeSet constructor. We did neither of that.

Let’s implement the Comparable interface in the Employee class and try again.

Output

As we can see from the output, the Employee objects are now automatically sorted by the TreeSet in ascending order of the id field.

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

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

References:
Java 8 TreeSet

About the author

Leave a Reply

Your email address will not be published.