TreeMap按照value排序

treemap默認是按照ket排序,底層紅黑樹實現

public static void sortByValue() {
        Map<String,Integer> map = new TreeMap<String, Integer>();
        map.put("a", 1);
        map.put("d", 2);
        map.put("b", 3);
        map.put("c",0);

        List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());

        Collections.sort(list,new Comparator<Map.Entry<String,Integer>>() {
            //升序排序
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String,Integer> o2) {
                return o1.getValue().compareTo(o2.getValue());
            }
        });

        for (Map.Entry<String, Integer> e: list) {
            System.out.println(e.getKey()+":"+e.getValue());
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章