首页 > 解决方案 > 如何访问存储在对象中的映射值

问题描述

我正在尝试创建一个哈希图,但似乎找不到在地图中检索属性值的方法。

我通过在子类中使用实例变量来创建新的键值对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”类的钥匙?

标签: javahashmap

解决方案


使用 Java 8,这是一个不错的解决方案

students.values()
    .stream()
    .filter(student -> student.getCategory() == 'A')
    .collect(Collectors.toList());

如果您想打印类别而不是学生列表,您可以添加mapforeach中介操作

students.values()
    .stream()
    .map(Student::getCategory)
    .filter(cat -> cat == 'A')
    .foreach(System.out::println);

推荐阅读