如何获取HashMap中Category属性为'A'的Student对象对应的键
如何从HashMap中检索Category属性为'A'的键
嘿,这问题不难解决,我来给你捋清楚!首先你得确保你的Student类有一个能访问Category属性的getter方法——毕竟咱们得能拿到这个属性的值才能做判断嘛。
第一步:给Student类添加getter方法
你的Student类需要这样一个方法来获取category属性:
public class Student { private String name; private String address; private char category; // 你的构造方法 public Student(String name, String address, char category) { this.name = name; this.address = address; this.category = category; } // 关键:获取category的getter方法 public char getCategory() { return category; } // 如果你需要的话,也可以添加其他属性的getter和toString()方法 }
方法1:传统循环遍历(兼容Java 8之前版本)
如果你的项目还在使用Java 8之前的版本,用这种传统循环的方式就很稳妥:
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')); // 用来存符合条件的键 List<String> categoryAKeys = new ArrayList<>(); // 遍历HashMap的每个键值对 for (Map.Entry<String, Student> entry : students.entrySet()) { // 判断当前Student的category是否为'A' if (entry.getValue().getCategory() == 'A') { // 符合条件就把键(比如"0001")加入列表 categoryAKeys.add(entry.getKey()); } } // 输出结果 System.out.println("Category为'A'的键:" + categoryAKeys); // 输出内容:Category为'A'的键:[0001, 0003]
方法2:Java 8+ 流API(更简洁优雅)
要是你的项目用的是Java 8或更高版本,用流API来处理会更清爽,代码可读性也更强:
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')); // 一行代码完成筛选、提取和收集 List<String> categoryAKeys = students.entrySet() .stream() .filter(entry -> entry.getValue().getCategory() == 'A') // 过滤出category为'A'的条目 .map(Map.Entry::getKey) // 提取这些条目的键 .collect(Collectors.toList()); // 把结果收集到列表里 // 输出结果 System.out.println("Category为'A'的键:" + categoryAKeys);
两种方法都能帮你拿到想要的结果,选哪种就看你的Java版本和代码风格偏好啦~
内容的提问来源于stack exchange,提问作者Guggugu
相关产品推荐
相关产品推荐

