TreeMap Constructors – How to Create TreeMap in Java

This example shows how to create a new TreeMap object using the TreeMap constructors in Java. This example also shows the use of various TreeMap constructors.

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

The TreeMap class in Java provides several constructors using which we can create new objects of it.

1. Create new empty TreeMap object

The default constructor of the TreeMap class creates a new and empty map object.

The map will use the natural ordering of its keys. The keys inserted into this map object must implement the Comparable interface.

Output

As you can see from the output, all the entries of the TreeMap are automatically sorted in the natural ordering of the keys (which is an ascending order for the type Integer).

2. Create new TreeMap with custom Comparator

As we have seen, the default constructor uses the natural ordering of the keys to sort the entries. In case you want to provide the custom order, there is an overloaded constructor that accepts a custom Comparator object.

This constructor creates an empty TreeMap object whose entries will be ordered according to the specified comparator object instead of the natural ordering of the keys.

Output

3. Creating a TreeMap from another Map (HashMap, LinkedHashMap)

There is an overloaded constructor that accepts a Map object as an argument.

It creates a new TreeMap object having the same mappings as the specified map object. The keys of the specified map object must implement the Comparable interface for this to work or else the ClassCastException will be thrown. The mappings copied from the map will be automatically sorted by the TreeMap according to the natural order of the keys.

Convert HashMap to TreeMap Example

Output

As you can see from the output, all HashMap entries are automatically sorted in the TreeMap object.

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

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

References:
Java 8 TreeMap

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