Map排序

Map<String, String> map = new HashMap<String, String>();
        map.put("a", "c");
        map.put("b", "b");
        map.put("c", "a");

        // 經過ArrayList構造函數把map.entrySet()轉換成list
        List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>(map.entrySet());
        // 經過比較器實現比較排序
        Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
            @Override
            public int compare(Map.Entry<String, String> mapping1, Map.Entry<String, String> mapping2) {
                return mapping1.getKey().compareTo(mapping2.getKey());
            }
        });

        for (Map.Entry<String, String> mapping : list) {
            System.out.println(mapping.getKey() + " :" + mapping.getValue());
        }
相關文章
相關標籤/搜索