我有一个地图条目列表
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>
有效,但这会导致编译器稍后发出“未经检查的方法调用”警告。