Skip to content

Create New TreeSet in Java using TreeSet Constructors

This example shows how to create new TreeSet objects in Java using the TreeSet constructors. The example also shows how to use different TreeSet constructors.

How to create new TreeSet objects in Java using TreeSet constructors?

The TreeSet class in Java provides several constructors using which you can create new TreeSet objects.

1. Create new and empty TreeSet object

The default constructor of the TreeSet class creates a new empty TreeSet object.

The elements of this set will be sorted automatically according to their natural ordering.

The above statement will create a new TreeSet object whose elements will be of type Integer and will be sorted automatically in ascending order i.e. natural order for the type Integer.

Output

2. Create a new TreeSet object with custom Comparator

The default constructor creates a set object whose elements will be sorted by the natural ordering. If you do not want the elements natural ordering, you can specify a custom Comparator object using the below given constructor.

This constructor creates a new and empty TreeSet object whose elements will be sorted according to the custom comparator.

The below given example shows how to sort TreeSet Integer object elements in descending orders using a comparator.

Output

3. How to create new TreeSet from another Set like HashSet?

Use below given copy constructor to create a TreeSet from any existing collection object.

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

The below given example shows how to convert HashSet to TreeSet using this constructor.

Output

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

Important Note: All elements of the specified collection must implement the Comparable interface for this constructor to work. If they have not, java.lang.ClassCastException: cannot be cast to java.lang.Comparable exception will be thrown.

This example is a part of the Java TreeSet 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.