Program to Convert HashMap to TreeMap in Java

HashMap is a part of Java’s collection since Java 1.2. It provides the basic implementation of Map interface of Java which stores the data in (Key, Value) pairs. To access a value in HashMap, one must know its key. HashMap is known as HashMap because it uses a technique Hashing for storage of data.

The TreeMap in Java is used to implement Map interface and NavigableMap along with the Abstract Class. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. This proves to be an efficient way of sorting and storing the key-value pairs.

Below are methods to convert HashMap to TreeMap in Java in such a way that the resultant TreeMap should contain all mappings of the HashMap, sorted by their natural ordering of keys.



Examples:

Input: HashMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}
Output: TreeMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}

Input: HashMap: {1=1, 2=2, 3=3}
Output: TreeMap: {1=1, 2=2, 3=3}

Below are methods to convert HashMap to TreeMap in Java:

  1. In Java 8: This method includes converting the HashMap to a Stream and collects elements of a stream in a TreeMap using Stream.collect() method which accepts a collector.

    Algorithm:

    1. Get the HashMap to be converted.
    2. Get the entries from the hashMap
    3. Convert the map entries into stream
    4. Using Collectors, collect the entries and convert it into TreeMap
    5. Now collect the TreeMap
    6. Return the formed TreeMap

    Program:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java Program to convert
    // HashMap to TreeMap in Java 8
      
    import java.util.*;
    import java.util.stream.*;
      
    class GFG {
      
        // Generic function to construct a new 
        // TreeMap from HashMap
        public static <K, V> Map<K, V> convertToTreeMap(Map<K, V> hashMap)
        {
            Map<K, V>
                treeMap = hashMap
                              // Get the entries from the hashMap
                              .entrySet()
      
                              // Convert the map into stream
                              .stream()
      
                              // Now collect the returned TreeMap
                              .collect(
                                  Collectors
      
                                      // Using Collectors, collect the entries
                                      // and convert it into TreeMap
                                      .toMap(
                                          Map.Entry::getKey,
                                          Map.Entry::getValue,
                                          (oldValue,
                                           newValue)
                                              -> newValue,
                                          TreeMap::new));
      
            // Return the TreeMap
            return treeMap;
        }
      
        public static void main(String args[])
        {
            // Create a HashMap
            Map<String, String> hashMap = new HashMap<>();
      
            // Add entries to the HashMap
            hashMap.put("1", "Geeks");
            hashMap.put("2", "forGeeks");
            hashMap.put("3", "A computer Portal");
      
            // Print the HashMap
            System.out.println("HashMap: " + hashMap);
      
            // construct a new TreeMap from HashMap
            Map<String, String> treeMap = convertToTreeMap(hashMap);
      
            // Print the TreeMap
            System.out.println("TreeMap: " + treeMap);
        }
    }

    chevron_right

    
    

    Output:

    HashMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}
    TreeMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}
    
  2. Using Plain Java: In this method, either pass HashMap instance to the TreeMap constructor or to putAll() method. This will directly create the TreeMap from the HashMap.

    Algorithm:

    1. Get the HashMap to be converted.
    2. Create a new TreeMap
    3. Pass the hashMap to putAll() method of treeMap
    4. Return the formed TreeMap

    Program:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java Program to convert
    // HashMap to TreeMap in Java 8
      
    import java.util.*;
    import java.util.stream.*;
      
    class GFG {
      
        // Generic function to construct a 
        // new TreeMap from HashMap
        public static <K, V> Map<K, V> convertToTreeMap(Map<K, V> hashMap)
        {
            // Create a new TreeMap
            Map<K, V> treeMap = new TreeMap<>();
      
            // Pass the hashMap to putAll() method
            treeMap.putAll(hashMap);
      
            // Return the TreeMap
            return treeMap;
        }
      
        public static void main(String args[])
        {
            // Create a HashMap
            Map<String, String> hashMap = new HashMap<>();
      
            // Add entries to the HashMap
            hashMap.put("1", "Geeks");
            hashMap.put("2", "forGeeks");
            hashMap.put("3", "A computer Portal");
      
            // Print the HashMap
            System.out.println("HashMap: " + hashMap);
      
            // construct a new TreeMap from HashMap
            Map<String, String> treeMap = convertToTreeMap(hashMap);
      
            // Print the TreeMap
            System.out.println("TreeMap: " + treeMap);
        }
    }

    chevron_right

    
    

    Output:



    HashMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}
    TreeMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}
    
  3. Using Google’s Guava library: Guava also provides a TreeMap implementation which can be used to create an empty TreeMap instance.

    Algorithm:

    1. Get the HashMap to be converted.
    2. Create a new TreeMap using Maps.newTreeMap() of Guava library
    3. Pass the hashMap to putAll() method of treeMap
    4. Return the formed TreeMap

    Program:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java Program to convert
    // HashMap to TreeMap in Java 8
      
    import com.google.common.collect.*;
    import java.util.*;
    import java.util.stream.*;
      
    class GFG {
      
        // Generic function to construct a
        // new TreeMap from HashMap
        public static <K extends Comparable, V> Map<K, V> 
                           convertToTreeMap(Map<K, V> hashMap)
        {
            // Create a new TreeMap
            Map<K, V> treeMap = Maps.newTreeMap();
      
            // Pass the hashMap to putAll() method
            treeMap.putAll(hashMap);
      
            // Return the TreeMap
            return treeMap;
        }
      
        public static void main(String args[])
        {
            // Create a HashMap
            Map<String, String> hashMap = new HashMap<>();
      
            // Add entries to the HashMap
            hashMap.put("1", "Geeks");
            hashMap.put("2", "forGeeks");
            hashMap.put("3", "A computer Portal");
      
            // Print the HashMap
            System.out.println("HashMap: " + hashMap);
      
            // construct a new TreeMap from HashMap
            Map<String, String> treeMap = convertToTreeMap(hashMap);
      
            // Print the TreeMap
            System.out.println("TreeMap: " + treeMap);
        }
    }

    chevron_right

    
    

    Output:

    HashMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}
    TreeMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}
    
  4. Conversion between incompatible types: This method can be used if the required TreeMap is of the different type than the HashMap. In this, the conversion needs to be done manually.

    Algorithm:

    1. Get the HashMap to be converted.
    2. Create a new TreeMap
    3. For each entry of the hashMap:
      • Convert the Key and the Value into the desired type by casting
      • Insert the converted pait by put() method of treeMap
    4. Return the formed TreeMap

    Program:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java Program to convert
    // HashMap to TreeMap in Java 8
      
    import java.util.*;
    import java.util.stream.*;
      
    class GFG {
      
        // Function to construct a new TreeMap from HashMap
        public static Map<Integer, String> 
                   convertToTreeMap(Map<String, String> hashMap)
        {
            // Create a new TreeMap
            Map<Integer, String> treeMap = new TreeMap<>();
      
            // Convert the HashMap to TreeMap manually
            for (Map.Entry<String, String> e : hashMap.entrySet()) {
                treeMap.put(Integer.parseInt(e.getKey()), e.getValue());
            }
      
            // Return the TreeMap
            return treeMap;
        }
      
        public static void main(String args[])
        {
            // Create a HashMap
            Map<String, String> hashMap = new HashMap<>();
      
            // Add entries to the HashMap
            hashMap.put("1", "Geeks");
            hashMap.put("2", "forGeeks");
            hashMap.put("3", "A computer Portal");
      
            // Print the HashMap
            System.out.println("HashMap: " + hashMap);
      
            // construct a new TreeMap<Integer, String>
            // from HashMap<String, String>
            Map<Integer, String> treeMap = convertToTreeMap(hashMap);
      
            // Print the TreeMap
            System.out.println("TreeMap: " + treeMap);
        }
    }

    chevron_right

    
    

    Output:

    HashMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}
    TreeMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}
    


My Personal Notes arrow_drop_up

Technical Content Engineer at GeeksForGeeks

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.