This post will discuss 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, whereas a Red-Black tree implements TreeMap.

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, the 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. Following are a few ways to convert HashMap to TreeMap in Java:

1. Using Java 8

The idea is to convert HashMap to a stream and collect elements of a stream in a TreeMap using the 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}

 
Here’s an equivalent version without using the Stream API.

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. Using Guava Library

Guava also provides TreeMap implementation, which can 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 and above, as demonstrated below:

Download  Run Code

Or even better,

Download  Run Code

That’s all about converting HashMap to TreeMap in Java.

 
Exercise: Convert HashMap to LinkedHashMap in Java