Let's say i have 2 classes.
Course Class
public class Course {
private int id;
private String name;
}
Student Class
public class Student {
private int id;
private String name;
private List<Course> courses;
}
I have List<Student>
and each Student
is enrolled in multiple courses.
I need to filter out results using Java 8 stream API's as following.
Map<courseId, List<Student>>
I have tried below, but no success:
1st Approach
Map<Integer, List<Student>> courseStudentMap = studentList.stream()
.collect(Collectors.groupingBy(
student -> student.getCourses().stream()
.collect(Collectors.groupingBy(Course::getId))));
2nd Approach
Map<Integer, List<Student>> courseStudentMap = studentList.stream()
.filter(student -> student.getCourses().stream()
.collect(Collectors.groupingBy(
Course::getId, Collectors.mapping(Student::student, Collectors.toList()))));
Converting complete Map<Key, Value> into Stream: This can be done with the help of Map. entrySet() method which returns a Set view of the mappings contained in this map. In Java 8, this returned set can be easily converted into a Stream of key-value pairs using Set. stream() method.
Java Stream map We can change stream elements into a new stream; the original source is not modified. The map method returns a stream consisting of the results of applying the given function to the elements of a stream. The map is an itermediate operation.
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())));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With