0
0
JavaHow-ToBeginner · 3 min read

How to Sort HashMap by Key in Java - Simple Guide

To sort a HashMap by its keys in Java, you can convert it to a TreeMap which naturally sorts keys in ascending order. Alternatively, use Java 8 streams to sort entries by key and collect them into a LinkedHashMap to preserve order.
📐

Syntax

Use TreeMap to sort a HashMap by keys automatically. Or use streams to sort and collect entries.

  • new TreeMap<>(hashMap): creates a sorted map by keys.
  • hashMap.entrySet().stream().sorted(Map.Entry.comparingByKey()): sorts entries by key using streams.
  • Collectors.toMap() with LinkedHashMap::new: collects sorted entries preserving order.
java
TreeMap<K, V> sortedMap = new TreeMap<>(hashMap);

LinkedHashMap<K, V> sortedMap = hashMap.entrySet()
    .stream()
    .sorted(Map.Entry.comparingByKey())
    .collect(Collectors.toMap(
        Map.Entry::getKey,
        Map.Entry::getValue,
        (e1, e2) -> e1,
        LinkedHashMap::new
    ));
💻

Example

This example shows how to sort a HashMap by its keys using both TreeMap and Java 8 streams.

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

public class SortHashMapByKey {
    public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<>();
        map.put("banana", 2);
        map.put("apple", 5);
        map.put("orange", 3);
        map.put("mango", 4);

        // Using TreeMap
        TreeMap<String, Integer> sortedByTreeMap = new TreeMap<>(map);
        System.out.println("Sorted by TreeMap:");
        sortedByTreeMap.forEach((k, v) -> System.out.println(k + " = " + v));

        // Using Streams
        LinkedHashMap<String, Integer> sortedByStream = map.entrySet()
            .stream()
            .sorted(Map.Entry.comparingByKey())
            .collect(Collectors.toMap(
                Map.Entry::getKey,
                Map.Entry::getValue,
                (e1, e2) -> e1,
                LinkedHashMap::new
            ));

        System.out.println("\nSorted by Streams:");
        sortedByStream.forEach((k, v) -> System.out.println(k + " = " + v));
    }
}
Output
Sorted by TreeMap: apple = 5 banana = 2 mango = 4 orange = 3 Sorted by Streams: apple = 5 banana = 2 mango = 4 orange = 3
⚠️

Common Pitfalls

One common mistake is expecting the original HashMap to maintain order after sorting, but HashMap does not keep any order. You must use a sorted map like TreeMap or a LinkedHashMap to preserve sorted order.

Another pitfall is not specifying the correct Collector when using streams, which can cause the order to be lost.

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

public class WrongSorting {
    public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<>();
        map.put("b", 2);
        map.put("a", 1);

        // Wrong: sorting stream but collecting to HashMap loses order
        Map<String, Integer> wrongSorted = map.entrySet()
            .stream()
            .sorted(Map.Entry.comparingByKey())
            .collect(Collectors.toMap(
                Map.Entry::getKey,
                Map.Entry::getValue
            ));

        System.out.println("Wrong sorted map (order not guaranteed): " + wrongSorted);

        // Right: collect to LinkedHashMap to keep order
        Map<String, Integer> rightSorted = map.entrySet()
            .stream()
            .sorted(Map.Entry.comparingByKey())
            .collect(Collectors.toMap(
                Map.Entry::getKey,
                Map.Entry::getValue,
                (e1, e2) -> e1,
                LinkedHashMap::new
            ));

        System.out.println("Right sorted map: " + rightSorted);
    }
}
Output
Wrong sorted map (order not guaranteed): {a=1, b=2} Right sorted map: {a=1, b=2}
📊

Quick Reference

  • TreeMap: Automatically sorts keys in natural order.
  • Streams + LinkedHashMap: Sort entries and preserve order.
  • HashMap: Does not maintain any order.

Key Takeaways

Use TreeMap to sort a HashMap by keys easily and get a sorted map.
Java 8 streams can sort entries by key and collect them into a LinkedHashMap to preserve order.
HashMap itself does not maintain any order, so sorting requires conversion.
Always collect sorted streams into LinkedHashMap, not HashMap, to keep order.
TreeMap sorts keys in natural ascending order by default.