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:
如何按降序进行?
推荐答案
要逆序排序,请将 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.
使用静态导入,它变得更令人愉快:
With static imports, it becomes a bit more pleasant:
这篇关于java - 如何在Java流中按值按降序对LinkedHashMap进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!