java - 通过按值对地图进行排序来获取 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
解决方案
这里:
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());
}
推荐阅读
- stack-trace - 如何在使用 retrace.jar 去混淆的 android / R8 堆栈跟踪中读取 lambda?
- sql - PostgreSQL 复合外键“列列表不得包含重复项”
- database - 如何在wordpress中运行代码来处理数据库
- python - 如何将逗号分隔的数字字符串转换为数字?
- python - 如何使用于转义字符串中字符的反斜杠不计数
- javascript - 从数组中提取值的意外行为:所有值都是 2
- graphql - 为 React Admin 3.7 实现 GraphQL 数据提供程序
- asp.net-core - JWT 在 .NET Core Web API 中过期太快
- angular - 是否在延迟加载模块时创建 2 个服务实例
- java - 在 Java 中使用序列化和反序列化时如何处理类更改