Convert HashMap to TreeMap in Java

In this post, we will see how to convert HashMap to TreeMap in Java. The resultant TreeMap should contain all mappings of the HashMap, sorted by their natural ordering of keys.


We know that HashMap is implemented using a Hash Table while TreeMap is implemented by Red-Black tree.

HashMap is much faster than TreeMap (O(1) time versus O(log(n)) time for inserting and searching but offers no ordering guarantees like TreeMap. In a TreeMap, map is ordered according to the natural ordering of its keys or a specified Comparator in the TreeMap’s constructor.

If we want near-HashMap performance and insertion-order iteration, we can use LinkedHashMap.

Below are few ways to convert HashMap to TreeMap in Java –


1. Java 8

The idea is to convert HashMap to a Stream and collect elements of a stream in a TreeMap using Stream.collect() method which accepts a collector.

We can use collector returned by Collectors.toMap() method that accepts TreeMap constructor reference TreeMap::new.

Download   Run Code


{BLUE=#0000FF, GREEN=#008000, RED=#FF0000}


2. Plain Java

To construct a new TreeMap from HashMap, we can either pass HashMap instance to the TreeMap constructor or to putAll() method.


3. Google’s Guava library

Guava also provides TreeMap implementation which can be used to create an empty TreeMap instance.


4. Conversion between incompatible types

If HashMap and TreeMap is expected to have incompatible types of keys or values, we’ll need to convert them manually:

Download   Run Code


{1=ONE, 2=TWO, 3=THREE}

We can do better in Java 8 as illustrated below:

Download   Run Code

or even better,

Download   Run Code

Exercise: Convert HashMap to LinkedHashMap in Java

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)


Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of