Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream - Nested Collection - Convert to Map

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()))));
like image 900
Ankur Singhal Avatar asked Apr 30 '18 07:04

Ankur Singhal


People also ask

Can we convert map to stream?

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.

Does stream map change the original array?

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.


1 Answers

 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())));
like image 155
Eugene Avatar answered Jan 01 '23 01:01

Eugene