反向排序HashMap? [英] sort HashMap in reverse?
本文介绍了反向排序HashMap?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我碰到了这种方法,该方法能够按值对HashMaps进行排序.
So I came across this method which is able to sort HashMaps by value.
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
return map.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1,
LinkedHashMap::new
));
}
我想在Comparator
上使用reversed()
方法,但是我似乎找不到合适的放置位置.
I want to use the reversed()
method on the Comparator
but I can't seem to find the right place to put it.
推荐答案
应在comparingByValue()
返回的Comparator
上调用reversed()
方法.不幸的是,Java的类型推断在这里分解,因此您必须指定通用类型:
The reversed()
method should be called on the Comparator
returned by comparingByValue()
. Java's type inference breaks down here, unfortunately, so you'll have to specify the generic types:
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue
(Map<K, V> map) {
return map.entrySet()
.stream()
.sorted(Map.Entry.<K, V> comparingByValue().reversed())
// Type here -----^ reversed() here -------^
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1,
LinkedHashMap::new
));
}
这篇关于反向排序HashMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文