Map<Integer, List<LoopLineDataVO>> 这种类型的map怎么根据key排序

img


因为查询的值分组了 然后数据排序乱了,
如图 map中如何根据integer的值来进行倒叙排序


public Map<Integer, List> sort(Map<Integer, List> map){
        //Java8中使用Stream对map进行排序
        Map<Integer, List> result = map.entrySet().stream()
                .sorted(Map.Entry.comparingByKey(
                        //倒序
                        Comparator.reverseOrder()
                ))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue, LinkedHashMap::new));
        return result;
    }

HashMap永远是散乱分布的,做不到排序。
可以用TreeMap,它自带排序功能。


public static void main(String[] args) throws ParseException {
        User user = new User("张三");
        User user2 = new User("李四");
        List<User> list1 = new ArrayList<>();
        List<User> list2 = new ArrayList<>();
        list1.add(user);
        list1.add(user2);
        list2.add(user);
        list2.add(user2);

        Map<Integer, List<User>> map = new HashMap<>();
        map.put(9999, list1);
        map.put(8888, list2);
        map.put(6666, list2);
        map.put(7777, list2);

        Map<Integer, List<User>> resultMap = new TreeMap<>((str1, str2) -> str2.compareTo(str1));
        resultMap.putAll(map);
        resultMap.forEach((key,value)-> System.out.println(key+":"+value));
        System.out.println(123);
    }

转换成TreeMap进行排序,希望可以帮到你’

map定义改为:Map<Integer, List> = new TreeMap<>();

map按key排序直接把map转成 TreeMap 就行了