所以我遇到了这个方法,它能够按值对 HashMap 进行排序。
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
));
}
我想使用reversed()
方法上的Comparator
但我似乎找不到合适的地方来放置它。
The reversed()
方法应该被调用Comparator
由返回comparingByValue()
。不幸的是,Java 的类型推断在这里崩溃了,因此您必须指定泛型类型:
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
));
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)