首页 > 解决方案 > hashMap 中的值排序

问题描述

我需要对 HashMap 进行排序,其值如下
4,2021-05-29 1,2021-06-01 2,2021-07-01 3,2021-08-01 和 1,2021-05-29 2,2021- 06-01 3,2021-07-01 4,2021-08-01 我尝试了以下代码,但不起作用

`List<Map.Entry<Long, Date> > list =  new LinkedList<Map.Entry<Long, Date> > 
(creditRecMap.entrySet());
    creditRecMap.entrySet();
        // Sort the list
        Collections.sort(list, new Comparator<Map.Entry<Long, Date> >() {
            public int compare(Map.Entry<Long, Date> o1,
                               Map.Entry<Long, Date> o2)
            {
                return (o2.getValue()).compareTo(o1.getValue());
            }
        });
         
        // put data from sorted list to hashmap
        HashMap<Long, Date> temp = new LinkedHashMap<Long, Date>();
        for (Map.Entry<Long, Date> aa : list) {
            temp.put(aa.getKey(), aa.getValue());
        }
        
     

标签: javahashmap

解决方案


这将为您提供按值排序的 Map 条目流。
creditRecMap.entrySet().stream.sorted((entry1, entry2) -> entry1.getValue().getTime() - entry2.getValue().getTime());


推荐阅读