Header Ads Widget

Sorting HashMap Values Using Java 8 Streams


Problem Scenario

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

HashMap Input 

Name - Sam          Age - 42

Name - John          Age - 43

Name - Adam        Age - 18

Name - Bob           Age - 50

Name - Micheal     Age - 16

Output Expected

Key : Micheal  Value : 16

Key : Adam          Value : 18

Key : Sam          Value : 42

Key : John          Value : 43

Key : Bob          Value : 50

Sorting using Streams & Comparator

The sortedMap method will take the hashmap as input and using the Comparator and the Sorted method the values of the hashmap will be sorted. The sorted values will be added to the newly created LinkedHashMap. We have created the LinkedHashMap instead of the Hashmap because the LinkedHashMap will keep the insertion order and Hashmap doesn't keep the insertion order. 

public Map<String, Integer> sortedMap(Map<String, Integer> map) {
   return map.entrySet().stream().sorted((v1, v2) -> v1.getValue()
               (Map.Entry::getKey, Map.Entry::getValue,
                    (k, v) -> k, LinkedHashMap::new));

Once we have sorted the values of the Hashmap we will print the sorted values in the console. Complete code changes are attached below.

package com.sandbox.code;

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

public class HashMapSort {

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

        mapVal = new HashMapSort().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((v1, v2) -> v1.getValue().compareTo(v2.getValue()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (k, v) -> k, LinkedHashMap::new));


Console Output

HashMap Value Sorting Output

Post a Comment