Java Collection How to - Sort Map values by key








Question

We would like to know how to sort Map values by key.

Answer

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
/*  ww w .java 2 s .  c  om*/
public class Main {

  public static void main(String[] args) {
    HashMap<String, String> hm = new HashMap<String, String>();
    hm.put("4", "four");
    hm.put("3", "three");
    hm.put("1", "one");
    hm.put("2", "two");

    Map<String, String> treeMap = new TreeMap<String, String>(hm);
    System.out.println(treeMap);
  }
}

The code above generates the following result.