1. Introduction
In Java, a Map is a collection of key-value pairs, and it’s often required to sort it by its keys. The TreeMap class from the Java Collections Framework provides a convenient way to store key-value pairs in sorted order of their keys. Additionally, one can use streams in Java 8 and above to sort a Map by its keys.
2. Program Steps
1. Create a HashMap and populate it with some key-value pairs.
2. Print the original Map.
3. Convert the HashMap to a TreeMap to sort it by keys.
4. Alternatively, use Java 8 Stream API to sort the HashMap by keys.
5. Print the sorted Map.
3. Code Program
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class SortMapByKey {
public static void main(String[] args) {
// Step 1: Create a HashMap and populate it with some key-value pairs
Map<String, Integer> unsortedMap = new HashMap<>();
unsortedMap.put("Banana", 3);
unsortedMap.put("Apple", 5);
unsortedMap.put("Cherry", 1);
// Step 2: Print the original Map
System.out.println("Original Map: " + unsortedMap);
// Step 3: Convert the HashMap to a TreeMap to sort it by keys
Map<String, Integer> sortedMap = new TreeMap<>(unsortedMap);
// Step 4: Alternatively, use Java 8 Stream API to sort the HashMap by keys
// Map<String, Integer> sortedMap = unsortedMap.entrySet()
// .stream()
// .sorted(Map.Entry.comparingByKey())
// .collect(Collectors.toMap(
// Map.Entry::getKey,
// Map.Entry::getValue,
// (e1, e2) -> e1,
// LinkedHashMap::new));
// Step 5: Print the sorted Map
System.out.println("Sorted Map by Keys: " + sortedMap);
}
}
Output:
Original Map: {Banana=3, Apple=5, Cherry=1} Sorted Map by Keys: {Apple=5, Banana=3, Cherry=1}
4. Step By Step Explanation
Step 1: A HashMap named unsortedMap is created and initialized with some key-value pairs.
Step 2: The original Map is printed to the console. Note that HashMap does not maintain any order of its keys or values.
Step 3: The unsortedMap is converted to a TreeMap named sortedMap using the TreeMap constructor, which sorts the key-value pairs by their keys.
Step 4: Alternatively, using the Java 8 Stream API, we can sort the unsortedMap by its keys. This step is commented out in the code and is not necessary if Step 3 is used.
Step 5: The sorted Map by keys, sortedMap, is printed to the console.