java - 按键升序排序 map

标签 java sorting hashmap map-function

我正在尝试根据键按升序对 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/

相关文章:

java - Spring 测试 : which is the common way of creating and maintaining test data?

javascript - 制表符从表中获取数据,但在数组中

python - 高效地找到对象中的最高值,并识别对象

java - ArrayList和HashMap容量增长的区别

java - 如何对预期在小程序安全管理器中运行的 Java 代码进行单元测试

java - dbf CREATE TABLE 抛出 java.sql.SQLException : Syntax error: Stopped parse at

regex - 如何使用 grep 打印出唯一匹配的计数?

java - 太阳http服务器: access from the Handler to an object created externally

java - 查找给定单词中字符的重复次数

java - Jakarta Regexp 和 Java 6 java.util.regex 之间的差异