java - 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());
}
解决方案
这将为您提供按值排序的 Map 条目流。
creditRecMap.entrySet().stream.sorted((entry1, entry2) -> entry1.getValue().getTime() - entry2.getValue().getTime());
推荐阅读
- pine-script - 是否可以在 pine 脚本中执行以下计算?
- python - 在 Django 中检测代理或 VPN 用户
- kotlin - 我应该给 AlertDialog.Builder 什么上下文?
- sql - seq.nextval 作为全局变量 Oracle
- javascript - 我如何将我的现成玩家我的头像显示到个人资料图片中
- python - 如何检查两个输入变量是否在两个不同列表中的相同位置并返回有效?
- python - 将嵌套字典转换为键值
- gitlab - GitLab API:获取与问题相关的分支
- android - 程序似乎无法定位片段来初始化地图
- iis - 请求被中止:无法在 windows server 2012 上创建 SSL/TLS 安全通道