Header Ads Widget

Sorting HashMap Keys Using Java 8 Streams

Problem Scenario

The below HashMap contains the key as the person's name and the value as person's age. We need to sort the hashmap using the Key (According to the person's name).

HashMap Input 

Name - Sam              Age - 42

Name - Adam            Age - 43

Name - Chandler      Age - 18

Name - Bob              Age - 50

Name - Micheal        Age - 16

Output Expected

Key : Adam          Value : 43

Key : Bob          Value : 50

Key : Chandler  Value : 18

Key : Micheal Value : 16

Key : Sam          Value : 42

Sorting Using Streams & java.util.Map.Entry

The sortedMap() method will loop the each value and key in the map and sort by using the comparingByValue method from the java.util.Map.Entry. Once it is sorted then a new LinkedHashMap will be created and add to it. We are not using a HashMap here because HashMap will not store the data in the insertion order and LinkedHashMap will store the data in the insertion order. We can also use TreeMap instead of the LinkedHashMap but TreeMap are slower than the LinkedHashMap. 


    public Map<String, Integer> sortedMap(Map<String, Integer> map) {
        return map.entrySet().stream().sorted(Entry.comparingByKey())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (k, v) -> k, LinkedHashMap::new));
    }



The sorting could be done using a Comparable also like this .sorted((v1, v2) -> v1.getKey().compareTo(v2.getKey())) .Once we sorted and added the values into the LinkedHashMap then we will print the values to the console. The complete code changes are attached below.


HashMapKeySort.java
package com.sandbox.code;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

public class HashMapKeySort {

    public static void main(String[] args) {
        Map<String, Integer> mapVal = new HashMap<>();
        mapVal.put("Sam", 42);
        mapVal.put("Adam", 43);
        mapVal.put("Chandler", 18);
        mapVal.put("Bob", 50);
        mapVal.put("Micheal", 16);

        mapVal = new HashMapKeySort().sortedMap(mapVal);
        mapVal.forEach((k, v) -> System.out.println("Key : " + k + "    Value : " + v));
    }

    public Map<String, Integer> sortedMap(Map<String, Integer> map) {
        return map.entrySet().stream().sorted(Entry.comparingByKey())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (k, v) -> k, LinkedHashMap::new));
    }
}


Console Output

Post a Comment

0 Comments