Java program to sort map by keys

https:/‮/‬www.theitroad.com

To sort a Map by its keys in Java, you can create a new TreeMap with a custom Comparator that compares keys based on their natural order. Here's an example program that demonstrates how to do this:

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class SortMapByKeys {
    public static void main(String[] args) {
        // Create a HashMap with some key-value pairs
        Map<String, Integer> unsortedMap = new HashMap<>();
        unsortedMap.put("Bob", 3);
        unsortedMap.put("Alice", 1);
        unsortedMap.put("Charlie", 2);

        // Sort the map by keys using a TreeMap
        Map<String, Integer> sortedMap = new TreeMap<>(unsortedMap);

        // Print the sorted map
        for (Map.Entry<String, Integer> entry : sortedMap.entrySet()) {
            System.out.println(entry.getKey() + " => " + entry.getValue());
        }
    }
}

In this program, we first create a HashMap called unsortedMap with some key-value pairs. We then create a new TreeMap called sortedMap and pass in unsortedMap as a parameter. The TreeMap will automatically sort the keys of the HashMap in ascending order based on their natural order.

Finally, we iterate through the sorted map using a for-each loop and print out each key-value pair. When you run this program, the output should be:

Alice => 1
Bob => 3
Charlie => 2