How to Sort a Java Map by Value Using LinkedHashMap and Lambdas

This article explains why HashMap cannot preserve entry order, introduces LinkedHashMap to maintain insertion order, and provides both classic and lambda‑based Java solutions—including detailed code snippets—to sort a Map by its values efficiently.

FunTester
FunTester
FunTester
How to Sort a Java Map by Value Using LinkedHashMap and Lambdas

Why use LinkedHashMap

Unlike HashMap, which does not guarantee any ordering of its entries, LinkedHashMap maintains a doubly‑linked list of entries. This preserves the insertion order (or access order if configured) while providing the same O(1) performance for get/put operations. The trade‑off is a modest increase in memory usage.

Classic sorting approach

To obtain a map sorted by its values, the traditional method performs three steps:

Convert the original HashMap into a List<Map.Entry<K,V>> using hashMap.entrySet().

Sort the list with Collections.sort and a comparator that compares the entry values.

Iterate over the sorted list and insert each entry into a new LinkedHashMap, which preserves the order of insertion.

public class MapFunTester {
    public static void main(String[] args) {
        Map<String, Integer> hashMap = new HashMap<>();
        hashMap.put("fun", 3);
        hashMap.put("funtest", 7);
        hashMap.put("funtester", 9);
        hashMap.put("f", 1);

        // Convert to list and sort by value
        List<Map.Entry<String, Integer>> list = new ArrayList<>(hashMap.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> e1, Map.Entry<String, Integer> e2) {
                return e1.getValue() - e2.getValue();
            }
        });

        // Preserve sorted order in a LinkedHashMap
        Map<String, Integer> linkedHashMap = new LinkedHashMap<>();
        for (Map.Entry<String, Integer> entry : list) {
            linkedHashMap.put(entry.getKey(), entry.getValue());
        }
        System.out.println(linkedHashMap);
    }
}

Lambda / Stream solution (Java 8+)

The same result can be expressed in a single pipeline using streams. The key is Collectors.toMap with a mapSupplier that creates a LinkedHashMap so the ordering is retained.

LinkedHashMap<String, Integer> sortedMap = hashMap.entrySet()
    .stream()
    .sorted(Map.Entry.comparingByValue())
    .collect(Collectors.toMap(
        Map.Entry::getKey,
        Map.Entry::getValue,
        (v1, v2) -> v1,               // merge function (not used here)
        LinkedHashMap::new));
System.out.println(sortedMap);

Collectors.toMap overloads

Collectors.toMap

provides three overloads:

toMap(keyMapper, valueMapper)
toMap(keyMapper, valueMapper, mergeFunction)
toMap(keyMapper, valueMapper, mergeFunction, mapSupplier)

The four parameters of the most complete overload are:

keyMapper : function that produces the map key from a stream element.

valueMapper : function that produces the map value.

mergeFunction : resolves conflicts when duplicate keys are encountered.

mapSupplier : a Supplier that creates the desired map implementation (e.g., LinkedHashMap::new).

When converting a HashMap to a sorted map, supplying LinkedHashMap::new is essential; otherwise the collector would return a plain HashMap and the ordering would be lost.

Extended use‑case: converting a List to a Map

The same collector pattern is frequently used to transform a List into a Map. The example below maps each string to its length and keeps the later value when duplicate keys appear.

public static void main(String[] args) {
    List<String> list = Arrays.asList("f", "fun", "funtest", "funtester");
    Map<String, Integer> map = list.stream()
        .collect(Collectors.toMap(
            s -> s,               // keyMapper: the string itself
            s -> s.length(),      // valueMapper: length of the string
            (oldVal, newVal) -> newVal)); // keep the later value on conflict
    System.out.println(map);
}

This produces a map where each word is associated with its length, e.g., {f=1, fun=3, funtest=7, funtester=9}.

Summary

Using LinkedHashMap together with either the classic Collections.sort workflow or the modern stream‑based approach enables deterministic ordering of map entries based on values or keys. The stream version is more concise but requires understanding the full Collectors.toMap overload, especially the mapSupplier argument that preserves the desired ordering.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaLambdaStreamsCollectorsLinkedHashMapMap Sorting
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.