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
));
相关文章