In Java, standard HashMap collections are unordered. If you want to sort a map by its keys, you can easily wrap it in a TreeMap. However, sorting a map by its **values** requires more work. You must extract the entry set, sort it, and stream or insert it back into an ordered map representation.

In this guide, we will look at how to sort a HashMap by values using the classic collections sorting approach and the modern Java 8 Stream API.

Illustration representing sorting entry lists in Java collections

1. Classic Way: Collections.sort() on Entry Lists

Before Java 8, the standard recipe to sort a map by value was to copy the entries to a list, sort the list using a custom Comparator, and insert them sequentially into a LinkedHashMap (which preserves insertion order):

private static void sortByValuesWithoutStream(Map<String, Integer> map) {
    // 1. Copy entries to a list
    ArrayList<Map.Entry<String, Integer>> entries = new ArrayList<>(map.entrySet());

    // 2. Sort the entry list
    Collections.sort(entries, (o1, o2) -> {
        return o2.getValue().compareTo(o1.getValue()); // Descending order
    });

    // 3. Put elements back into an insertion-ordered LinkedHashMap
    LinkedHashMap<String, Integer> sortedMap = new LinkedHashMap<>();
    entries.forEach(entry -> sortedMap.put(entry.getKey(), entry.getValue()));

    System.out.println(sortedMap); // Prints sorted map representation
}

2. Modern Way: Java 8 Streams

With Java 8, you can stream the entry set directly, apply sorting operations using Map.Entry.comparingByValue(), and process or collect the values:

private static void sortByvaluesWithStream(Map<String, Integer> map) {
    map.entrySet().stream()
            // Sort entries using custom value comparator
            .sorted(Map.Entry.comparingByValue((o1, o2) -> o2.compareTo(o1))) 
            .forEach(entry -> System.out.print(entry.getKey() + "=" + entry.getValue() + " "));
}

Full Implementation

Below is the complete Java program comparing both sorting layouts:

package io.practise.map;

import java.util.*;

public class TestMapSorting {
    public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<>();
        map.put("Abhishek", 95);
        map.put("Rahul", 12);
        map.put("Prateek", 50);
        map.put("Anil", 58);

        System.out.println("Classic Sorting Result:");
        sortByValuesWithoutStream(map);

        System.out.println("Stream Sorting Result:");
        sortByvaluesWithStream(map);
    }
}

Conclusion

Sorting a map by value is a common operations task. The classic approach using LinkedHashMap is perfect if you need to return a sorted map object, while the Stream API is ideal for quick logging, filtering, or processing elements on the fly.