【发布时间】:2021-05-28 15:17:12
【问题描述】:
我需要使用以下值对 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());
}
【问题讨论】:
-
在您的数据中,
key会根据值的顺序发生变化,这是故意的吗?什么不起作用? -
地图一般不能按值排序,
HashMap根本不能排序。您的尝试可能有效,但您试图在不复制的情况下对看似底层的HashMap进行排序。 (另请注意,Comparator.comparing(Map.Entry::getValue)会更易读。) -
这是故意的@ThomasJungblut
-
排序是什么意思?您的意思是具有最低值的键首先出现吗?如果键具有相同的值,您将如何对它们进行排序?你会检查键映射到的值吗?
-
@DarkEagle 是的,我首先需要键 1 的最低日期,然后是第二个日期,然后是第三个