1. Introduction
In Java, a HashMap does not maintain any order of its elements. However, there might be situations where we need to sort the HashMap by its keys. To achieve this, we can use a TreeMap. The TreeMap class from the Java Collections Framework provides a convenient way to store key-value pairs in a sorted order of their keys. In this post, we will see how to sort a HashMap by its keys using a TreeMap.
2. Program Steps
1. Create a HashMap and add some key-value pairs to it.
2. Create a TreeMap object and pass the HashMap to its constructor. The TreeMap will be sorted according to the natural ordering of its keys.
3. Iterate through the TreeMap and print the sorted key-value pairs.
3. Code Program
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class SortHashMapByKeys {
public static void main(String[] args) {
// Step 1: Create a HashMap and add some key-value pairs
Map<String, Integer> unsortedMap = new HashMap<>();
unsortedMap.put("Banana", 3);
unsortedMap.put("Apple", 1);
unsortedMap.put("Cherry", 2);
// Step 2: Create a TreeMap object and pass the HashMap to its constructor
Map<String, Integer> sortedMap = new TreeMap<>(unsortedMap);
// Step 3: Iterate through the TreeMap and print the sorted key-value pairs
System.out.println("HashMap after sorting by keys:");
for (Map.Entry<String, Integer> entry : sortedMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
Output:
HashMap after sorting by keys: Apple: 1 Banana: 3 Cherry: 2
4. Step By Step Explanation
Step 1: We create a HashMap named unsortedMap and populate it with some key-value pairs. The keys are of type String, and the values are of type Integer.
Step 2: A TreeMap named sortedMap is created, and the unsortedMap is passed to its constructor. The TreeMap automatically sorts the key-value pairs of the unsortedMap according to the natural ordering of its keys (alphabetically in this case).
Step 3: An enhanced for loop is used to iterate over the entrySet of the sortedMap. Within the loop, the sorted key-value pairs are printed to the console.