[英]Getting null by sorting map by values
I am getting null
when I am trying to get keys to match with sorted values.当我试图让键与排序值匹配时,我得到
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();
}
Result:结果:
Key = null, Value = 40
Key = null, Value = 75
Key = null, Value = 80
Key = null, Value = 80
Key = null, Value = 90
Here:这里:
map.get(y)
y
is one of the map's values, but remember what get
does? y
是地图的值之一,但还记得get
是做什么的吗? It takes a key of the map, and gives you the value associated with that key, not the other around!它需要 map 的键,并为您提供与该键关联的值,而不是其他键!
You should sort the map entries (ie key value pairs) by their value, rather than taking all the values out, and ignoring all the keys.您应该按值对 map条目(即键值对)进行排序,而不是取出所有值并忽略所有键。 That way you can get the key of each pair easily in the loop.
这样您就可以在循环中轻松获取每对的密钥。
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());
}
your map stored strings as its key.您的 map 存储字符串作为其密钥。 you get values by integers from it, it of cause returns null~
你从它获取整数值,它的原因返回null~
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.