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

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