首页 > 解决方案 > 通过按值对地图进行排序来获取 null

问题描述

当我null试图让键与排序值匹配时,我得到了。

public class Linked_L {
static Map<String, Integer> map = new HashMap<>();

public static void sortbyValue(){
        ArrayList<Integer> sortedValues = new ArrayList<>(map.values());
        Collections.sort(sortedValues);
        for (Integer y: sortedValues)
            System.out.println("Key = " +map.get(y) + ", Value = " + y);
    }

public static void main(String args[])
{
    // putting values in the Map
    map.put("Jayant", 80);
    map.put("Abhishek", 90);
    map.put("Anushka", 80);
    map.put("Amit", 75);
    map.put("Danish", 40);

    // Calling the function to sortbyKey
    sortbyValue();
}

结果:

Key = null, Value = 40
Key = null, Value = 75
Key = null, Value = 80
Key = null, Value = 80
Key = null, Value = 90

标签: java

解决方案


这里:

map.get(y)

y是地图的值之一,但还记得是什么get吗?它需要地图的一个,并为您提供与该键关联的值,而不是其他键!

您应该按值对映射条目(即键值对)进行排序,而不是取出所有值并忽略所有键。这样您就可以在循环中轻松获取每对的密钥。

ArrayList<Map.Entry<String, Integer>> sortedEntries = new ArrayList<>(map.entrySet());
Collections.sort(sortedEntries, Comparator.comparing(Map.Entry::getValue));
for (var entry: sortedEntries) {
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

推荐阅读