按键升序对地图进行排序

Ala*_*ook 5 java sorting hashmap map-function

我正在尝试根据键按升序对地图进行排序。鉴于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");
Run Code Online (Sandbox Code Playgroud)

我想要订单:

0, zero
1, one
3, three
5, five
Run Code Online (Sandbox Code Playgroud)

我编写了以下代码来完成此任务:

    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;
}
Run Code Online (Sandbox Code Playgroud)

但是,当我打电话时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>>)
Run Code Online (Sandbox Code Playgroud)

我已经编写了类似的代码(效果很好)来按值排序(更改Entry.comparingByKey()Entry.comparingByValue()),但由于某种原因,当我尝试按键排序时,出现上述错误。

我怎样才能解决这个问题?

谢谢

And*_*ner 4

你需要进行K比较并按它进行排序;并且上的界限V是错误的(但无论如何都是不必要的)。

public <K extends Comparable<? super K>, V> Map<K, V> sortByKeyInAscendingOrder(Map<K, V> map)
Run Code Online (Sandbox Code Playgroud)

请注意,更简单的方法可能是:

return new LinkedHashMap<>(new TreeMap<>(map));
Run Code Online (Sandbox Code Playgroud)

或者

return map.entrySet().stream()
    .sorted(Entry.comparingKey())
    .collect(toMap(k -> k, v -> v, LinkedHashMap::new));
Run Code Online (Sandbox Code Playgroud)