How to sort Map values by key in Java?

后端 未结 15 2199
野性不改
野性不改 2020-11-22 08:26

I have a Map that has strings for both keys and values.

Data is like following:

\"question1\", \"1\"
\"question9\", \"1\"
\"que

15条回答
  •  粉色の甜心
    2020-11-22 09:18

    If you already have a map and would like to sort it on keys, simply use :

    Map treeMap = new TreeMap(yourMap);
    

    A complete working example :

    import java.util.HashMap;
    import java.util.Set;
    import java.util.Map;
    import java.util.TreeMap;
    import java.util.Iterator;
    
    class SortOnKey {
    
    public static void main(String[] args) {
       HashMap hm = new HashMap();
       hm.put("3","three");
       hm.put("1","one");
       hm.put("4","four");
       hm.put("2","two");
       printMap(hm);
       Map treeMap = new TreeMap(hm);
       printMap(treeMap);
    }//main
    
    public static void printMap(Map map) {
        Set s = map.entrySet();
        Iterator it = s.iterator();
        while ( it.hasNext() ) {
           Map.Entry entry = (Map.Entry) it.next();
           String key = (String) entry.getKey();
           String value = (String) entry.getValue();
           System.out.println(key + " => " + value);
        }//while
        System.out.println("========================");
    }//printMap
    
    }//class
    

提交回复
热议问题