Write a Java Program to Sort map by keys

Sorting a map by its keys can be easily done in Java by utilizing the TreeMap class.

TreeMap is a sorted map implementation that automatically sorts the entries based on the natural ordering of the keys or by a custom Comparator.


Let’s take a look at an example of how to sort a map by keys using TreeMap:

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

public class MapSorter {
    public static void main(String[] args) {
        // create an unsorted map
        Map<String, Integer> unsortedMap = Map.of("c", 3, "b", 2, "a", 1);

        // create a TreeMap that sorts the map by its keys
        Map<String, Integer> sortedMap = new TreeMap<>(unsortedMap);

        // print the sorted map
        System.out.println(sortedMap);
    }
}

In the above example, we first create an unsorted map with three key-value pairs.

We then create a TreeMap that takes the unsorted map as an argument.

The TreeMap automatically sorts the entries based on the natural ordering of the keys, which is alphabetical order in this case.

Finally, we print the sorted map to the console.

If we run the above program, we should see the following output:

{a=1, b=2, c=3}

As we can see, the TreeMap has sorted the map by its keys in alphabetical order.

If we want to sort the map by keys in reverse order, we can use a custom Comparator that reverses the natural ordering.

Here’s an example:

import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

public class MapSorter {
    public static void main(String[] args) {
        // create an unsorted map
        Map<String, Integer> unsortedMap = Map.of("c", 3, "b", 2, "a", 1);

        // create a TreeMap that sorts the map by its keys in reverse order
        Map<String, Integer> sortedMap = new TreeMap<>(Comparator.reverseOrder());
        sortedMap.putAll(unsortedMap);

        // print the sorted map
        System.out.println(sortedMap);
    }
}

In this example, we create a custom Comparator that reverses the natural ordering of the keys.

We then create a TreeMap that uses this Comparator to sort the map in reverse order.

Finally, we put all the entries from the unsorted map into the sorted map and print the result to the console.

If we run the above program, we should see the following output:

{c=3, b=2, a=1}

As we can see, the TreeMap has sorted the map by its keys in reverse order.


In conclusion, sorting a map by its keys in Java can be easily done using the TreeMap class.

TreeMap automatically sorts the entries based on the natural ordering of the keys or by a custom Comparator.

By using TreeMap, we can easily sort a map in ascending or descending order based on the keys.