Java 对HashMap进行反向排序?
所以我遇到了这个方法,它能够按值对HashMaps进行排序Java 对HashMap进行反向排序?,java,sorting,generics,hashmap,comparator,Java,Sorting,Generics,Hashmap,Comparator,所以我遇到了这个方法,它能够按值对HashMaps进行排序 public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) { return map.entrySet() .stream() .sorted(Map.Entry.comparingByValue
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
));
}
publicstatic应该在comparingByValue()
返回的比较器上调用reversed()
方法。不幸的是,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
));
}
public static@jornverne不起作用“不起作用”?“不工作”如何?@LewBloch.sorted(Map.Entry.comparingByValue().reversed())不编译。穆雷尼克溶液works@BenArnao这就是为什么在你的问题中加入你尝试过的东西,以及清楚地描述你尝试过的东西不起作用的原因。谢谢,这是我需要的。我尝试在那个地方使用reversed(),但没有成功,因为我必须指定类型。