Sort Map by Value in Java

In this Java core tutorial, we show you how to implement the Java method to sort elements of a Map object by its entry value in the Java program.

Implement method to sort a map by value

Firstly, create a new class named MapUtils and implement a method sortMapByValue() which expects a Map as argument and returns a sorted Map.

MapUtils.java

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class MapUtils {

    public static Map<String, String> sortMapByValue(Map<String, String> map) {
        if(map == null) {
            return null;
        }
        
        Map<String, String> sortedMap = new LinkedHashMap<>();

        List<Map.Entry<String, String>> mapEntryList = new ArrayList<>(map.entrySet());

        Collections.sort(mapEntryList, new Comparator<Map.Entry<String, String>>() {
            @Override
            public int compare(Map.Entry<String, String> entry1, Map.Entry<String, String> entry2) {
                return entry1.getValue().compareTo(entry2.getValue());
            }
        });

        for (Map.Entry<String, String> entry :mapEntryList) {
            sortedMap.put(entry.getKey(), entry.getValue());
        }

        return sortedMap;
    }
}

Using MapUtils.sortMapByValue() method to sort map

In the following example Java program we use the MapUtils.sortMapByValue() static method above to sort a map.

SortMapByValueExample.java

import java.util.LinkedHashMap;
import java.util.Map;

public class SortMapByValueExample {
    public static void main(String[] args) {
        Map<String, String> sampleMap = new LinkedHashMap<>();
        sampleMap.put("value1", "b");
        sampleMap.put("value2", "c");
        sampleMap.put("value3", "a");
        sampleMap.put("value4", "d");

        System.out.println("Sample Input Map:");
        for (Map.Entry entry: sampleMap.entrySet()) {
            System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
        }

        // sort the map
        Map<String, String> sortedMap = MapUtils.sortMapByValue(sampleMap);

        System.out.println("\nSorted Map:");
        for (Map.Entry entry: sortedMap.entrySet()) {
            System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
        }
    }
}
The output is:
Sample Input Map:
Key: value1, Value: b
Key: value2, Value: c
Key: value3, Value: a
Key: value4, Value: d

Sorted Map:
Key: value3, Value: a
Key: value1, Value: b
Key: value2, Value: c
Key: value4, Value: d

Happy Coding 😊

Sort Map by Key in Java