A HashMap does not maintain any order. To sort it, you must create a new ordered map or view.
Sorting a HashMap by Key
The easiest and most efficient way is to add the HashMap into a TreeMap, which automatically sorts entries by key.
Example (Sorting by Key)
Map<Integer, String> map = new HashMap<>(); // Initialize HashMap
map.put(2, “Hi”);
map.put(1, “Hello”);
// TreeMap sorts entries by key
Map<Integer, String> sortedMap = new TreeMap<>(map);
System.out.println(sortedMap);
✔ Why this works
TreeMapstores entries in natural key order- Sorting happens automatically
- Time complexity: O(n log n)
Sorting a HashMap by Value
Sorting by value requires converting the map into a stream of entries, sorting them, and collecting the result into a LinkedHashMap to preserve order.
Example (Sorting by Value)
Map<Integer, List<Integer>> map = new HashMap<>();
map.put(2, Arrays.asList(2, 3, 4));
map.put(1, Arrays.asList(5, 3, 4));
// Sort by value
Map<Integer, List<Integer>> sortedByValue =
map.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue(
Comparator.comparingInt(List::size)
))
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1,
LinkedHashMap::new
));
System.out.println(sortedByValue);
✔ Key points
stream()allows sorting logicLinkedHashMappreserves sorted order- Comparator defines how values are compared