How to sort a HashMap in Java

To sort a HashMap in Java, you can use the TreeMap class, which is a Map implementation that maintains its entries in ascending order, sorted according to the keys.

Here's an example of how you can sort a HashMap in Java:

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

public class Main {
  public static void main(String[] args) {
    // create a HashMap
    Map<String, Integer> map = new HashMap<>();
    map.put("apple", 5);
    map.put("banana", 3);
    map.put("cherry", 4);
    map.put("date", 1);
    map.put("elderberry", 2);

    // sort the HashMap using a TreeMap
    Map<String, Integer> sortedMap = new TreeMap<>(map);

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

This code creates a HashMap and adds several key-value pairs to it. It then creates a new TreeMap and passes the HashMap to the constructor of the TreeMap. This will create a new TreeMap that is sorted according to the keys of the HashMap. Finally, the code iterates through the entries of the sorted TreeMap and prints them to the console.

Note that the TreeMap class is a Red-Black tree based implementation of the Map interface, so it provides efficient operations for adding, removing, and searching for elements. However, it does not allow null keys or values.