我正在尝试根据键按升序对 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()
)但出于某种原因当我尝试按键排序时出现上述错误。
我该如何解决这个问题?
谢谢
最佳答案
您需要使 K
具有可比性才能按它排序; V
上的绑定(bind)是错误的(但无论如何都是不必要的)。
public <K extends Comparable<? super K>, V> Map<K, V> sortByKeyInAscendingOrder(Map<K, V> map)
请注意,更简单的方法可能是:
return new LinkedHashMap<>(new TreeMap<>(map));
或者
return map.entrySet().stream()
.sorted(Entry.comparingKey())
.collect(toMap(k -> k, v -> v, LinkedHashMap::new));
关于java - 按键升序排序 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54332498/