How can I sort Map values by key in Java?

To sort the values of a Map by key in Java, you can use the TreeMap class, which is a Map implementation that maintains its entries in ascending key order.

Here is an example of how to sort the values of a Map by key using a TreeMap:

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

public class Main {
  public static void main(String[] args) {
    Map<String, Integer> map = new HashMap<>();
    map.put("c", 3);
    map.put("a", 1);
    map.put("b", 2);

    Map<String, Integer> sortedMap = new TreeMap<>(map);
    System.out.println(sortedMap);  // Outputs "{a=1, b=2, c=3}"
  }
}

This code creates a HashMap and adds three entries to it. It then creates a TreeMap and initializes it with the entries of the HashMap. The TreeMap maintains the entries in ascending key order, so the resulting sortedMap has the keys in sorted order.

You can also use the TreeMap constructor that takes a Comparator as an argument to specify a custom ordering for the keys. For example, to sort the keys in descending order, you can use the following code:

Map<String, Integer> sortedMap = new TreeMap<>(Collections.reverseOrder());
sortedMap.putAll(map);
System.out.println(sortedMap);  // Outputs "{c=3, b=2, a=1}"