LinkedHashMap对key进行排序

对LinkedHashMap按key进行降序排序

public static void main(String[] args) {
    LinkedHashMap map = new LinkedHashMap();
    map.put("1","aaa");
    map.put("3","bbb");
    map.put("2","ccc");
    map.put("5","ddd");
    List> infoIds =new ArrayList>(map.entrySet());
    //排序
    Collections.sort(infoIds, new Comparator>() {
        public int compare(Map.Entry o1, Map.Entry o2) {
            String p1 =  o1.getKey();
            String p2 = o2.getKey();;
            return Integer.valueOf(p2)-Integer.valueOf(p1);//如果要升序, 改为return Integer.valueOf(p1)-Integer.valueOf(p2);
        }
    });
   //转换成新map输出
    LinkedHashMap newMap = new LinkedHashMap ();

    for(Map.Entry entity : infoIds){
        newMap.put(entity.getKey(), entity.getValue());
        System.out.println(entity.getKey());
    }
}

debug后的截图,已经降序排好

LinkedHashMap对key进行排序_第1张图片

你可能感兴趣的:(日常工作总结)