HashMap根据Key(升序a到z)排序


        Map<String, String> hMap = new HashMap<>();
        hMap.put("a", "1");
        hMap.put("z", "3");
        hMap.put("c", "5");
        hMap.put("k", "8");

        System.out.println("根据key升序排序");
        Map<String, String> sortByKeyResultMap = sortMapByKey(hMap);    //按Key进行排序
        Iterator<Map.Entry<String, String>> sortByKeyEntries = sortByKeyResultMap.entrySet().iterator();
        while (sortByKeyEntries.hasNext()) {
            Map.Entry<String, String> entry = sortByKeyEntries.next();
            System.out.println("Key = " + entry.getKey() + "------->Value = " + entry.getValue());
        }
    }
    /**
     * 使用 Map按key进行排序
     * @param map
     * @return
     */
    public static Map<String, String> sortMapByKey(Map<String, String> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }
        Map<String, String> sortMap = new TreeMap<>(new Comparator<String>() {
            public int compare(String obj1, String obj2) {
                return obj1.compareTo(obj2);//升序排序
            }
        });
        sortMap.putAll(map);
        return sortMap;
    }