How to Sort a Map by Key in Java

Comments · 4 Views

In Java, the Map interface represents a collection of key-value pairs, and it does not guar

However, there are situations where you may need to sort a Map by its keys. This article will explore various ways to achieve this, including using TreeMap, java sort map by key.

Using TreeMap to Sort a Map by Key
A TreeMap in Java is a sorted implementation of the Map interface, which maintains the keys in their natural order (ascending order by default). If you have a HashMap or LinkedHashMap and want to sort it by keys, you can pass it to a TreeMap.

Example Using TreeMap:
java
Copy
Edit
import java.util.*;

public class SortMapByKey {
public static void main(String[] args) {
Map<Integer, String> unsortedMap = new HashMap<>();
unsortedMap.put(3, "Apple");
unsortedMap.put(1, "Orange");
unsortedMap.put(2, "Banana");

// Sorting by key using TreeMap
Map<Integer, String> sortedMap = new TreeMap<>(unsortedMap);

// Display sorted map
sortedMap.forEach((key, value) -> System.out.println(key + " -> " + value));
}
}
Output:
rust
Copy
Edit
1 -> Orange
2 -> Banana
3 -> Apple
Sorting a Map by Key Using Java Streams
If you are using Java 8 or later, you can sort a Map by key using the Stream API. This method is useful if you want to keep the sorted order but store the data back into a LinkedHashMap to maintain insertion order.

Example Using Streams:
java
Copy
Edit
import java.util.*;
import java.util.stream.Collectors;

public class SortMapByKeyStream {
public static void main(String[] args) {
Map<String, Integer> unsortedMap = new HashMap<>();
unsortedMap.put("Banana", 2);
unsortedMap.put("Apple", 3);
unsortedMap.put("Orange", 1);

// Sorting using Stream API
Map<String, Integer> sortedMap = unsortedMap.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey()) // Sort by key
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1, // Merge function
LinkedHashMap::new)); // Preserve order

// Display sorted map
sortedMap.forEach((key, value) -> System.out.println(key + " -> " + value));
}
}
Output:
rust
Copy
Edit
Apple -> 3
Banana -> 2
Orange -> 1
Custom Sorting Using a Comparator
If you want to sort a Map by key in descending order, you can use a Comparator in the TreeMap constructor or modify the sorting function in the Stream API.

Example Using Comparator:
java
Copy
Edit
Map<Integer, String> sortedMap = new TreeMap<>(Collections.reverseOrder());
sortedMap.putAll(unsortedMap);
Alternatively, modify the stream sorting logic:

java
Copy
Edit
.sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
Conclusion
Sorting a Map by key in Java can be done using TreeMap, Stream API, or custom Comparator implementations. If you need an automatically sorted map, TreeMap is the best choice. However, if you prefer sorting dynamically while keeping insertion order, Java Streams with LinkedHashMap is an excellent approach.

Comments