Collections

Convert HashMap to TreeMap Java Example

Convert HashMap to TreeMap Java Example shows how to convert HashMap to TreeMap. Example also shows how to convert HashMap to TreeMap with custom Comparator.

How to convert HashMap to TreeMap in Java?

HashMap can be converted to TreeMap using below given ways.

1) Convert HashMap to TreeMap using TreeMap constructor

Use below given TreeMap constructor to convert from HashMap to TreeMap

This constructor creates a TreeMap containing same mapping as argument map. It also orders the elements according to the natural ordering of 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 HashMap to TreeMap. TreeMap by default orders the mappings according to the natural ordering of the keys.

2) Convert HashMap to TreeMap using putAll method of TreeMap

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

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

Output

How to provide custom Comparator while converting HashMap to TreeMap?

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

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

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

Output

What is the preferred way to convert HashMap to TreeMap?

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

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

 

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.