前言
我有两张关联表,一张学生表,一张教室表,学生表里有教室表的id,我需要查出来每个教室里的每个学生的信息 以此为前提,用jdk8的stream流来达到效果
讲解步骤
- 1、分别查出学生和教室的所有数据
List<Student> studentList = studentMapper.getAllList();
List<Classroom> classroomList = classroomMapper.getAllList();
- 2、将学生数据根据教室id分组,转成map ,教室id为key,对应的学生集合为value
Map<Long,List<Student>> detailStudent = studentList.stream().collect(Collectors.groupingBy(Student::getClassroomId));
- 3、将教室对应的学生集合做对应
List<ClassroomDTO> list = classroomList.stream().map(data -> {
List<LabelDTO> studentList = detailStudent.get(data.getId())
return new ClassroomDTO(data.getId(),data.getLabelGrpName(),studentList);
}).collect(Collectors.toList());