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

Output:

{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

Output:

{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

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz