Sorting a HashMap according to keys in Java

We are given the details of marks scored by students in form of a HashMap, where name of the student is the Key and marks scored is the Value. Our task is to sort the map according to the key values i.e the names of the students in the alphabetical(lexicographical) order.

Examples:

Input : Key = Jayant, Value = 80
        Key = Anushka, Value = 80
        Key = Amit, Value = 75
        Key = Abhishek, Value = 90
        Key = Danish, Value = 40
Output : Sorted Map according to Names:
         Key = Abhishek, Value = 90
         Key = Amit, Value = 75
         Key = Anushka, Value = 80
         Key = Danish, Value = 40
         Key = Jayant, Value = 80



Using TreeMap (putAll method)
The idea is to put all data of HashMap into a TreeMap. The TreeMap follows Red Black Tree based implementation. The map is sorted according to the natural ordering of its keys. Click here for More.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Code to sort Map by key value
import java.util.*;
class sortmapKey {
  
    // This map stores unsorted values
    static Map<String, Integer> map = new HashMap<>();
  
    // Function to sort map by Key
    public static void sortbykey()
    {
        // TreeMap to store values of HashMap
        TreeMap<String, Integer> sorted = new TreeMap<>();
  
        // Copy all data from hashMap into TreeMap
        sorted.putAll(map);
  
        // Display the TreeMap which is naturally sorted
        for (Map.Entry<String, Integer> entry : sorted.entrySet()) 
            System.out.println("Key = " + entry.getKey() + 
                         ", Value = " + entry.getValue());        
    }
      
    // Driver Code
    public static void main(String args[])
    {
        // putting values in the Map
        map.put("Jayant", 80);
        map.put("Abhishek", 90);
        map.put("Anushka", 80);
        map.put("Amit", 75);
        map.put("Danish", 40);
  
        // Calling the function to sortbyKey
        sortbykey();
    }
}

chevron_right


Output:

Key = Abhishek, Value = 90
Key = Amit, Value = 75
Key = Anushka, Value = 80
Key = Danish, Value = 40
Key = Jayant, Value = 80

Note: The TreeMap provides guaranteed log(n) time cost for the containsKey, get, put and remove operations.

Using TreeMap (Constructor)

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Code to sort Map by key value
import java.util.*;
class sortmapKey {
  
    // This map stores unsorted values
    static Map<String, Integer> map = new HashMap<>();
  
    // Function to sort map by Key
    public static void sortbykey()
    {
        // TreeMap to store values of HashMap
        TreeMap<String, Integer> sorted = new TreeMap<>(map);
  
        // Display the TreeMap which is naturally sorted
        for (Map.Entry<String, Integer> entry : sorted.entrySet()) 
            System.out.println("Key = " + entry.getKey() + 
                         ", Value = " + entry.getValue());        
    }
      
    // Driver Code
    public static void main(String args[])
    {
        // putting values in the Map
        map.put("Jayant", 80);
        map.put("Abhishek", 90);
        map.put("Anushka", 80);
        map.put("Amit", 75);
        map.put("Danish", 40);
  
        // Calling the function to sortbyKey
        sortbykey();
    }
}

chevron_right


Output:

Key = Abhishek, Value = 90
Key = Amit, Value = 75
Key = Anushka, Value = 80
Key = Danish, Value = 40
Key = Jayant, Value = 80

 
Using ArrayList

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Code to sort Map by key value
import java.util.*;
class sortmapKey {
  
    // This map stores unsorted values
    static Map<String, Integer> map = new HashMap<>();
  
    // Function to sort map by Key
    public static void sortbykey()
    {
        ArrayList<String> sortedKeys =
                    new ArrayList<String>(map.keySet());
          
        Collections.sort(sortedKeys); 
  
        // Display the TreeMap which is naturally sorted
        for (String x : sortedKeys) 
            System.out.println("Key = " + x + 
                        ", Value = " + map.get(x));     
    }
      
    // Driver Code
    public static void main(String args[])
    {
        // putting values in the Map
        map.put("Jayant", 80);
        map.put("Abhishek", 90);
        map.put("Anushka", 80);
        map.put("Amit", 75);
        map.put("Danish", 40);
  
        // Calling the function to sortbyKey
        sortbykey();
    }
}

chevron_right


Output:

Key = Abhishek, Value = 90
Key = Amit, Value = 75
Key = Anushka, Value = 80
Key = Danish, Value = 40
Key = Jayant, Value = 80

This article is contributed by DANISH KALEEM and Arnav Kr. Mandal. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up