我将尝试根据键值对对Map进行升序排序。给定以下Map
:
Map<Integer, String> map = new LinkedHashMap<Integer, String>();
map.put(5, "five");
map.put(1, "one");
map.put(3, "three");
map.put(0, "zero");
我想要这个订单:
0, zero
1, one
3, three
5, five
我写了下面的代码来实现这个功能:
public <K, V extends Comparable<? super V>> Map<K, V> sortByKeyInAscendingOrder(Map<K, V> map)
{
List<Entry<K, V>> list = new ArrayList<>(map.entrySet());
list.sort(Entry.comparingByKey());
Map<K, V> result = new LinkedHashMap<>();
for (Entry<K, V> entry : list) {
result.put(entry.getKey(), entry.getValue());
}
return result;
}
然而,当我调用
sort()
时,出现以下错误:The method sort(Comparator<? super Map.Entry<K,V>>) in the type List<Map.Entry<K,V>> is not applicable for the arguments (Comparator<Map.Entry<Comparable<? super Comparable<? super K>>,Object>>)
我曾写过相似代码(功能正常),用于按值排序(将 Entry.comparingByKey()
改为 Entry.comparingByValue()
),但是不知道为什么当我尝试按键排序时会出现上述错误。
我该如何解决这个问题?
谢谢。