java - 如何在Java 8中同时按自然顺序按desc中的值和键对Map进行排序
问题描述
有任何方法可以在同一操作中按键和值对 Map 进行排序。地图有价值{hover=1, solar=1, waterproof=3, storage=1, battery=2}
所以排序后的值应该是
{waterproof=3, battery=2, hover=1, solar=1, storage=1}
我正在尝试
Map mp = map.entrySet().stream()
.sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(newValue,oldValue) -> oldValue, LinkedHashMap::new))
//.sorted(Map.Entry.comparingByKey())
//.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
//(newValue,oldValue) -> oldValue, LinkedHashMap::new))
;
解决方案
使用创建比较器链thenComparing
:
Map mp = map.entrySet().stream()
.sorted(Collections.reverseOrder(Map.Entry.<String, Integer>comparingByValue())
.thenComparing(Map.Entry.comparingByKey()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(newValue, oldValue) -> oldValue, LinkedHashMap::new));
请注意,在这种情况下,您需要为第一个比较器指定显式类型参数,因为编译器无法在这种复杂情况下推断类型。
推荐阅读
- r - R帮助将非数字列转换为数字
- database - Postgres 序列正在生成负值作为主键
- python - 删除所有嵌套的 JSON 数组,除了最小日期的数组
- validation - Laravel 5:使用表单请求同时验证两个字段
- jquery - jQuery - 在不单击按钮的情况下触发函数
- multithreading - 是否可以在不锁定整个 HashMap 的情况下在线程之间共享 HashMap?
- c++ - 如何在 C++ 中使用带有 system() 函数的字符串变量
- arrays - 使用变量来保存 Bash 数组名称
- json - 在PowerShell中使用特定字符解析JSON文件
- python - 根据它们的交集在成对的项目之间找到一条路径