java - 如何访问存储在对象中的映射值
问题描述
我正在尝试创建一个哈希图,但似乎找不到在地图中检索属性值的方法。
我通过在子类中使用实例变量来创建新的键值对Student
。
从子类创建时,如何检索共享相同属性值“A”的所有条目?
Map<String, Student> students = new HashMap<>();
students.put("0001", new Student("Mike Myers","60 Hey", 'A'));
students.put("0002", new Student("Victor Hughes","21 ddd", 'F'));
students.put("0003", new Student("Elisabeth Carter","56 fff", 'A'));
如果我做
for (Map.Entry<String, Student> entry : students.entrySet())
{
System.out.println(entry.getValue());
}
然后我得到所有属性(名称、地址、类别)的值。所以我想知道如何获得只有“A”类的钥匙?
解决方案
使用 Java 8,这是一个不错的解决方案
students.values()
.stream()
.filter(student -> student.getCategory() == 'A')
.collect(Collectors.toList());
如果您想打印类别而不是学生列表,您可以添加map
和foreach
中介操作
students.values()
.stream()
.map(Student::getCategory)
.filter(cat -> cat == 'A')
.foreach(System.out::println);
推荐阅读
- file - 删除包含空格和特殊字符的文件名
- java - 如何在Android中使用坐标(纬度,经度)获取地点ID
- ubuntu - 所有 Vue 命令都返回“未知命令”
- tensorflow - 如何使用预训练变量初始化 TensorFlow 估计器的模型函数中的权重?
- c# - 如何在 asmx Web 服务中使用客户端证书实现 ssl 安全性
- node.js - 错误:生成 ngr ENOENT
- python - 将 Excel 电子表格导入 Pandas DataFrame 后,单元格中缺少换行符
- kylin - 我在启动 kylin 时收到错误“无法创建 /kylin。请确保用户有权访问 /kylin”
- php - SSL 仅适用于一半的站点
- java - 如何使用java在不重新启动服务器的情况下刷新缓存