Open In App

Sorting a HashMap according to keys in Java

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

We are given the details of marks scored by students in form of a HashMap, where the name of the student is the Key and the 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
 

Java




// 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();
    }
}


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) 

Java




// Java Code to sort Map by key value
import java.util.*;
class sortmapKey {
 
    // This map stores unsorted key
    static Map<String, Integer> map = new HashMap<>();
 
    // function to sort hashmap by keys
    public static Map<String, Integer>
    sortByKey(Map<String, Integer> hm)
    {
        // Create a list from elements of HashMap
        List<Map.Entry<String, Integer> > list
            = new LinkedList<Map.Entry<String, Integer> >(
                hm.entrySet());
 
        // Sort the list using lambda expression
        Collections.sort(
            list,
            (i1, i2) -> i1.getKey().compareTo(i2.getKey()));
 
        // put data from sorted list to hashmap
        HashMap<String, Integer> temp
            = new LinkedHashMap<String, Integer>();
        for (Map.Entry<String, Integer> aa : list) {
            temp.put(aa.getKey(), aa.getValue());
        }
        return temp;
    }
 
    // 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
        Map<String, Integer> hm1 = sortByKey(map);
 
        // print the sorted hashmap
        for (Map.Entry<String, Integer> en :
             hm1.entrySet()) {
            System.out.println("Key = " + en.getKey()
                               + ", Value = "
                               + en.getValue());
        }
    }
}


Output

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

Using ArrayList 

In this approach, we create a list of keys using ArrayList constructor. Then we sort the list using Collections.sort() method.

Java




// Java Code to sort Map by key value
import static java.util.stream.Collectors.*;
 
import java.lang.*;
import java.util.*;
import java.util.stream.*;
import java.util.stream.Collectors;
class sortmapKey {
 
    // This map stores unsorted values
    static Map<String, Integer> map = new HashMap<>();
 
    // Function to sort map by Key
    public static void sortbykey()
    {
        HashMap<String, Integer> temp
            = map.entrySet()
                  .stream()
                  .sorted((i1, i2)
                              -> i1.getKey().compareTo(
                                  i2.getKey()))
                  .collect(Collectors.toMap(
                      Map.Entry::getKey,
                      Map.Entry::getValue,
                      (e1, e2) -> e1, LinkedHashMap::new));
 
        // Display the HashMap which is naturally sorted
        for (Map.Entry<String, Integer> entry :
             temp.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();
    }
}


Output

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

 Using Java 8 Lambdas

Here we will change how we did sorting and will use lambda expression for sorting. The logic is the same, and even we also passed the comparator object but only using lambda.

Below is the implementation of the above approach:

Java





Output

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

Using Java 8 Streams

Here we will use streams to sort the map. We will use the stream() method to get the stream of entrySet followed by the lambda expression inside the sorted() method to sort the stream and finally, we will convert it into a map using toMap() method. Inside the toMap() method, we use the LinkedHashMap::new method reference to retain the sorted order of the map.

Java




// Java Code to sort Map by key value
import static java.util.stream.Collectors.*;
 
import java.lang.*;
import java.util.*;
import java.util.stream.*;
import java.util.stream.Collectors;
class sortmapKey {
 
    // This map stores unsorted values
    static Map<String, Integer> map = new HashMap<>();
 
    // Function to sort map by Key
    public static void sortbykey()
    {
        HashMap<String, Integer> temp
            = map.entrySet()
                  .stream()
                  .sorted((i1, i2)
                              -> i1.getKey().compareTo(
                                  i2.getKey()))
                  .collect(Collectors.toMap(
                      Map.Entry::getKey,
                      Map.Entry::getValue,
                      (e1, e2) -> e1, LinkedHashMap::new));
 
        // Display the HashMap which is naturally sorted
        for (Map.Entry<String, Integer> entry :
             temp.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();
    }
}


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.

 



Last Updated : 29 Apr, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads