Skip to content

Convert HashMap to TreeMap Java Example

Convert HashMap to TreeMap Java example shows how to convert HashMap to TreeMap using a constructor, the putAll method and a custom Comparator.

How to convert HashMap to TreeMap in Java?

The HashMap object can be converted to the TreeMap object using below given ways.

1) Convert HashMap to TreeMap using the TreeMap constructor

You can use the below given TreeMap constructor to convert.

This constructor creates a TreeMap object containing the same mapping as an argument map. It also orders the elements according to the natural ordering of the map’s keys.

Output

You may have noticed that when we printed the TreeMap entries, they are sorted by key i.e. sorted by student’s total marks in ascending order. This is a very desirable side effect of converting the TreeMap. The TreeMap class by default orders the mappings according to the natural ordering of the keys.

2) Using the putAll method of the TreeMap

You can convert using the default constructor of the TreeMap along with the putAll method.

This method copies all the mapping from the specified map to the TreeMap. It also orders the keys of the Map according to the natural ordering.

Output

How to provide custom Comparator while converting to the TreeMap?

If the HashMap keys are custom class objects and you want to sort it using custom Comparator while converting the TreeMap object, you can specify it using the TreeMap constructor as given below.

This constructor creates an empty TreeMap object whose keys will be sorted according to the specified custom Comparator.

In below given example, we are going to sort the Student objects according to total marks in descending order.

Output

What is the preferred way to convert?

If you want to sort the TreeMap objects by a custom Comparator, then you will have to use the putAll method. If you don’t, using the constructor that accepts the existing Map is the preferred way to convert as it produces cleaner code.

This example is a part of the Java HashMap tutorial with examples and Java TreeMap tutorial with examples.

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

About the author

Leave a Reply

Your email address will not be published.