按键按升序排序地图

问题描述 投票:4回答:4

我正在尝试根据键按升序对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())但由于某种原因,当我尝试按键排序时,我得到上述错误。

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

谢谢

java sorting hashmap map-function
4个回答
2
投票

你需要使K与它相当;而V的界限是错误的(但无论如何都是不必要的)。

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));

2
投票

method comparingByKey要求其密钥K类型参数为Comparable,而不是(必然)其值V

将绑定的? extends Comparable<? super K>V移动到K。更改

<K, V extends Comparable<? super K>>

<K extends Comparable<? super K>, V>

当然V也是Comparable也是可选的,但是让它自己引用,而不是K

V extends Comparable<? super V>

2
投票

使用TreeMap怎么样?它保持键按自然顺序排序:

https://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html

如果需要从现有地图创建它,请使用它的参数化构造函数:

TreeMap<Integer,String> treeMap = new TreeMap<>(map);

因为使用HashMap不保证顺序,LinkedHashMap维护插入顺序。要保持按键排序的地图,请使用TreeMap。


2
投票

您也可以尝试使用java 8流

Map<Integer, String> map = new LinkedHashMap<Integer, String>();

    map.put(5, "five");
    map.put(1, "one");
    map.put(3, "three");
    map.put(0, "zero");

    map = map.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

    System.out.println(map);  //{0=zero, 1=one, 3=three, 5=five}

或者你可以在forEach上使用Map

map.forEach((k,v)->System.out.println(k+"  "+v));
© www.soinside.com 2019 - 2024. All rights reserved.