对于这个玩具示例,我有一个带有id和名称的教室列表。我从数据源中取出这些教室,然后,对于每个教室,我都需要学习和教师列表。然后,我想创建另一个对象,该对象包含在classroom.id,classroom.name和List<Student>, List<Teacher>
中,称为Foo。问题是Foo是一个不可变对象,必须在所有信息可用时进行实例化。这是我尝试过的:
List<Classroom> classrooms = dataSource.fetchClassroomsById(classroomIds);
Map<Integer, Classroom> idToClassroom = new HashMap<>();
classrooms.stream()
.forEach(classroom -> {idToClassroom.put(classroom.getId(), classroom);});
//get all students and teachers that belong to set of classroomIds passed in
List<Student> students = dataSource.fetchStudentsById(classroomIds);
List<Teacher> teachers = dataSource.fetchTeachersById(classroomIds);
for (Student student : students) {
//gets the classroom for which student belongs. This is where I get stuck.
idsToClassroom.get(student.getClassRoomId())
}
...
基本上,我怎样才能有效而紧凑地构建我的Foo对象?
答案 0 :(得分:1)
使用Collectors.groupingBy
将学生和教师分组到相同教室ID的列表中。
List<Classroom> classrooms = dataSource.fetchClassroomsById(classroomIds);
List<Student> students = dataSource.fetchStudentsById(classroomIds);
List<Teacher> teachers = dataSource.fetchTeachersById(classroomIds);
Map<Integer, List<Student>> classroomIdToStudent = students.stream()
.collect(Collectors.groupingBy(Student::getClassroomId));
Map<Integer, List<Teacher>> classroomIdToTeacher = teachers.stream()
.collect(Collectors.groupingBy(Teacher::getClassroomId));
List<Foo> foos = classrooms.stream().map(c -> new Foo(c.getId(), c.getName(),
classroomIdToStudent.get(c.getId()), classroomIdToTeacher.get(c.getId()))).collect(Collectors.toList());