How to sort a LinkedHashMap by value in decreasing order in java stream?(java - 如何在Java流中按值按降序对LinkedHashMap进行排序?)
问题描述
要按升序排序,我可以使用:
To sort it int ascending order I can use:
myMap.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
如何按降序进行?
推荐答案
要逆序排序,请将 Comparator.reverseOrder() 作为参数传递给 comparingByValue.
To sort in reverse order, pass Comparator.reverseOrder() as parameter to comparingByValue.
要获得 LinkedHashMap,您必须专门请求一个带有 4 参数的 toMap().如果你没有指定你想要什么样的映射,你会得到默认的,当前恰好是一个HashMap.由于 HashMap 不保留元素的顺序,它肯定不适合你.
To get a LinkedHashMap, you must specifically request one with the 4-argument toMap(). If you don't specify what kind of a map you want, you will get whatever the default is, which currently happens to be a HashMap. Since HashMap doesn't preserve the order of elements, it will definitely not do for you.
myMap.entrySet().stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(x,y)-> {throw new AssertionError();},
LinkedHashMap::new
));
使用静态导入,它变得更令人愉快:
With static imports, it becomes a bit more pleasant:
myMap.entrySet().stream()
.sorted(comparingByValue(reverseOrder()))
.collect(toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(x,y)-> {throw new AssertionError();},
LinkedHashMap::new
));
这篇关于java - 如何在Java流中按值按降序对LinkedHashMap进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:java - 如何在Java流中按值按降序对LinkedHashMap进行排序?
基础教程推荐
- 如何对 Java Hashmap 中的值求和 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
