package com.cute.test;
    import java.util.Comparator;
    import java.util.Map;
    import java.util.TreeMap;
    public class SortMapTest {
    public static void main(String[] args) {
    Map tmap = new TreeMap();
    tmap.put(“abc”, “2”);
    tmap.put(“ace”, “3”);
    tmap.put(“cef”, “2”);
    tmap.put(“Weight”, “6”);
    tmap.put(“BLue”, “6”);
    tmap.put(“BLUe”, “6”);

    //对map利用key排序
    Map resMap = sortMapByKey(tmap);
    for (Map.Entry entry : resMap.entrySet()) {
    System.out.println(entry.getKey() + “ “ + entry.getValue());
    }
    }
    /*
    让 Map按key进行排序
    */
    public static Map sortMapByKey(Map map) {
    if (map == null || map.isEmpty()) {
    return null;
    }
    Map sortMap = new TreeMap(new MapKeyComparator());
    sortMap.putAll(map);
    return sortMap;
    }
    }
    //实现一个比较器类
    class MapKeyComparator implements Comparator {
    @Override
    public int compare(String s1, String s2) {
    return s1.compareTo(s2); //从小到大排序
    }
    }
    ——————————-
    版权声明:本文为CSDN博主「基咯咯」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/u010180815/article/details/78980844