我有一个地图条目列表
Map<String, Integer> map = new HashMap<>();
...(fill the map)...
List<Entry<String, Integer>> entries = new ArrayList<>(map.entrySet());
我希望按照这篇答案的方法根据数值对它进行排序,但要按相反的顺序排列。 当我这样做时:
Comparator<Entry<String, Integer>> cmp = Entry.comparingByValue();
entries.sort(cmp.reversed());
一切都很好。但是当我尝试将上述两行缩短为
entries.sort(Entry.comparingByValue().reversed());
编译器返回
error: incompatible types: Comparator<Entry<Object,V>> cannot be converted to Comparator<? super Entry<String,Integer>>
entries.sort(Entry.comparingByValue().reversed());
where V is a type-variable:
V extends Comparable<? super V>
这似乎很奇怪,因为Comparator的reversed()默认方法的实现只是将其转移到Collections.reverseOrder(),我可以将上面的行更改为
entries.sort(Collections.reverseOrder(Entry.comparingByValue()));
要工作。但是Entry.comparingByValue().reversed()
的正确类型是什么?
Comparator<Entry<String, Integer>> cmp = Entry.comparingByValue().reversed();
看起来并不起作用。省略类型参数Entry<String, Integer>
是可以的,但这会导致编译器后面出现“未经检查的方法调用”警告。