Java ProgramsCollectionsHashMap Sorting by Key

HashMap Sorting by Key in Java

intermediate·  Collections  ·  Map

Problem

A HashMap's iteration order isn't guaranteed, so getting entries out in a specific order means copying them somewhere sortable first, rather than relying on the map itself.

Given a HashMap already filled with unordered entries, print its entries sorted by key.

Input
put(Banana, 2), put(Apple, 5), put(Cherry, 3)
Output
Apple: 5, Banana: 2, Cherry: 3

Java Program

Java
import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; public class HashMapSortingByKey { public static void main(String[] args) { Map<String, Integer> scores = new HashMap<>(); scores.put("Banana", 2); scores.put("Apple", 5); scores.put("Cherry", 3); List<Map.Entry<String, Integer>> entries = new ArrayList<>(scores.entrySet()); entries.sort(Comparator.comparing(Map.Entry::getKey)); // sort the copy by key for (Map.Entry<String, Integer> entry : entries) { System.out.println(entry.getKey() + ": " + entry.getValue()); } } }

Output

Apple: 5 Banana: 2 Cherry: 3

Core Logic

Copying the map's entries into a List and sorting that List by key produces a sorted view without ever changing the original HashMap itself.

How It Works
  1. 1scores.entrySet() returns every key-value pair currently in the map, in whatever order the HashMap happens to store them.
  2. 2new ArrayList<>(scores.entrySet()) copies those entries into a List, which — unlike the entry set view — can be sorted directly.
  3. 3entries.sort(Comparator.comparing(Map.Entry::getKey)) sorts that List using each entry's key.
  4. 4Printing the sorted List afterward visits every entry in key order, even though the original scores map itself is never reordered.
Regardless of what order scores.entrySet() originally returned Banana, Apple, and Cherry in, sorting the copied list always prints Apple, then Banana, then Cherry.
💡

Key Point: This is different from starting with a TreeMap in the first place — here the map is already a HashMap, built and filled however it was, and the sorting happens afterward, on a separate copy, without touching the original map's structure.

Complexity
Time Complexity: O(n log n)Space Complexity: O(n)

Why: Copying the n entries into a List costs O(n), and sorting that List costs O(n log n), which dominates the total.

Key Concepts

HashMapentrySet()Comparator.comparing()

Approach 2: Java 8

Java
import java.util.HashMap; import java.util.Map; public class HashMapSortingByKeyStream { public static void main(String[] args) { Map<String, Integer> scores = new HashMap<>(); scores.put("Banana", 2); scores.put("Apple", 5); scores.put("Cherry", 3); // Sorts by key using the built-in comparator, no intermediate List needed scores.entrySet().stream() .sorted(Map.Entry.comparingByKey()) .forEach(entry -> System.out.println(entry.getKey() + ": " + entry.getValue())); } }

Output

Apple: 5 Banana: 2 Cherry: 3

Core Logic

Streaming the entrySet and sorting it with the built-in Map.Entry.comparingByKey() comparator expresses the same sort as a pipeline, without building an intermediate List by hand.

How It Works
  1. 1scores.entrySet().stream() opens a stream directly over the map's entries — no separate List needs to be built first.
  2. 2Map.Entry.&lt;String, Integer&gt;comparingByKey() is a ready-made comparator that compares two entries by their keys, replacing the manual Comparator.comparing(Map.Entry::getKey) call.
  3. 3.sorted(...) applies that comparator to produce a new, sorted stream, leaving the original map untouched.
  4. 4.forEach(...) prints each sorted entry directly, without collecting the sorted stream into a List first.
Streaming {Banana: 2, Apple: 5, Cherry: 3}'s entries through the key comparator sorts them the same way — Apple, then Banana, then Cherry.
💡

Key Point: Map.Entry.comparingByKey() is the standard-library comparator built specifically for this — reaching for it instead of Comparator.comparing(Map.Entry::getKey) is shorter and reads directly as 'compare entries by key'.

Complexity
Time Complexity: O(n log n)Space Complexity: O(n)

Why: sorted() still needs to buffer and sort all n entries internally before forEach() can process them in order, the same overall cost as the manual copy-and-sort.

Key Concepts

StreamMap.Entry.comparingByKey()forEach()

Related Programs