Home » How to Sort a Map by Its Values in Java

How to Sort a Map by Its Values in Java

numbers wall decor

Here’s how to sort a Map by its values in Java.

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;

public class SortingMaps {

    public static void main(String[] args) {
        Map<String, Integer> unsortedMap = Map.of(
                "three", 3,
                "one", 1,
                "four", 4,
                "five", 5,
                "two", 2
        );

        Map<String, Integer> sortedMap = sortByValue(unsortedMap);

        System.out.println(sortedMap);
    }

    private static Map<String, Integer> sortByValue(Map<String, Integer> unsortedMap) {
        Map<String, Integer> sortedMap = new LinkedHashMap<>();

        unsortedMap.entrySet().stream()
                   .sorted(Map.Entry.comparingByValue())
                   .forEach(entry -> sortedMap.put(entry.getKey(), entry.getValue()));

        return Collections.unmodifiableMap(sortedMap);
    }
}

If you have any questions, leave a comment or ask me on my social media.

Leave a Reply

Your email address will not be published. Required fields are marked *