Ank*_*hal 5 nested-loops java-8 java-stream
假设我有2节课.
课程班
public class Course {
private int id;
private String name;
}
Run Code Online (Sandbox Code Playgroud)
学生班
public class Student {
private int id;
private String name;
private List<Course> courses;
}
Run Code Online (Sandbox Code Playgroud)
我有List<Student>,每个人Student都注册了多门课程.
我需要使用Java 8流API过滤掉结果,如下所示.
Map<courseId, List<Student>>
Run Code Online (Sandbox Code Playgroud)
我在下面试过,但没有成功:
第一种方法
Map<Integer, List<Student>> courseStudentMap = studentList.stream()
.collect(Collectors.groupingBy(
student -> student.getCourses().stream()
.collect(Collectors.groupingBy(Course::getId))));
Run Code Online (Sandbox Code Playgroud)
第二种方法
Map<Integer, List<Student>> courseStudentMap = studentList.stream()
.filter(student -> student.getCourses().stream()
.collect(Collectors.groupingBy(
Course::getId, Collectors.mapping(Student::student, Collectors.toList()))));
Run Code Online (Sandbox Code Playgroud)
Map<Integer, List<Student>> result = studentsList
.stream()
.flatMap(x -> x.getCourses().stream().map(y -> new SimpleEntry<>(x, y.getId())))
.collect(Collectors.groupingBy(
Entry::getValue,
Collectors.mapping(Entry::getKey, Collectors.toList())));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
96 次 |
| 最近记录: |