I link another question I asked, where you see all the classes and data I'm working with.
Get non-repeating data from a query with Streams in java
I have to perform the following activity:
19.-showNumberOfSubjectsOfEachStudent()
It must show the number of subjects in which each student is enrolled. The output would be:
Number of subjects for each student: Baldomero: 2 Ana Guerra: 1 Germán Ginés: 2
I have tried, without any success, this:
public Map<String, Long> showNumberOfSubjectsOfEachStudent() {
return database.queryAllStudents().parallelStream()
.collect(Collectors.groupingBy(Student::getName, Collectors.mapping(Student::getGrades, Collectors.counting())));
}
My idea is to obtain the name of the students, although this data could be repeated, so I think it is better to simply obtain the student object as such, and then obtain the subjects and count them: theory very well, practice 0...
Thanks for the help.
What happens is that since getGrades() returns a list, if you use Collectors.mapping() you get a stream of lists, and when you count, it's always 1 (because it's 1 stream per student that contains many lists). So you have to use Collectors.flatMapping(), so that everything returns a single stream:
What I was telling you about parallelStream() is that, on the one hand, in many cases it can worsen performance, and on the other hand, depending on the operators, it might not return the expected results.