用Map帮我实现按照学号,姓名,班级查找学生信息
时间: 2023-08-04 20:07:01 浏览: 98
假设你已经有一个存储学生信息的数据结构,可以使用 `Map` 来实现按照学号、姓名、班级查找学生信息。以下是一个可能的实现:
```java
import java.util.*;
public class Student {
private int id;
private String name;
private String className;
// 构造函数、Getter 和 Setter 略
public static void main(String[] args) {
// 假设已经有了一些学生信息
List<Student> students = new ArrayList<>();
students.add(new Student(1, "Alice", "Class 1"));
students.add(new Student(2, "Bob", "Class 2"));
students.add(new Student(3, "Charlie", "Class 1"));
// 使用 Map 存储学生信息
Map<Integer, Student> idToStudent = new HashMap<>();
Map<String, List<Student>> nameToStudents = new HashMap<>();
Map<String, List<Student>> classToStudents = new HashMap<>();
for (Student student : students) {
idToStudent.put(student.getId(), student);
if (!nameToStudents.containsKey(student.getName())) {
nameToStudents.put(student.getName(), new ArrayList<>());
}
nameToStudents.get(student.getName()).add(student);
if (!classToStudents.containsKey(student.getClassName())) {
classToStudents.put(student.getClassName(), new ArrayList<>());
}
classToStudents.get(student.getClassName()).add(student);
}
// 按照学号查找学生信息
int id = 2;
if (idToStudent.containsKey(id)) {
Student student = idToStudent.get(id);
System.out.println("Found student by id: " + student);
} else {
System.out.println("Student not found by id: " + id);
}
// 按照姓名查找学生信息
String name = "Charlie";
if (nameToStudents.containsKey(name)) {
List<Student> studentsByName = nameToStudents.get(name);
System.out.println("Found students by name: " + studentsByName);
} else {
System.out.println("No student found by name: " + name);
}
// 按照班级查找学生信息
String className = "Class 1";
if (classToStudents.containsKey(className)) {
List<Student> studentsByClass = classToStudents.get(className);
System.out.println("Found students by class: " + studentsByClass);
} else {
System.out.println("No student found by class: " + className);
}
}
}
```
在这个实现中,我们使用了三个 `Map` 分别存储学号到学生、姓名到学生列表、班级到学生列表的映射关系。当需要查找学生信息时,只需要在对应的 `Map` 中查找即可。注意,由于一个姓名或班级可能对应多个学生,我们在 `nameToStudents` 和 `classToStudents` 中存储的值是一个学生列表。
阅读全文