Let's say I have a
Integer classCount = 0;
for (School school : schoolDistrict)
for (Student student : school.getStudents())
classCount += student.getClasses().size();
You can use
schoolDistrict.stream().flatMap(school -> school.getStudents().stream()) to get a
Stream<Student>. You can further do a second
flatMap() to get a
Stream<YourClass>. This is when you need to process each entity of nested collections. If you only need to count the amounts, you can use
sum() as the end operation.
flatMap() is the secret to unnesting or "flattening" nested collections.
Stream<MyClass> stream = schoolDistrict.stream().flatMap(s -> s.getStudents().stream()).flatMap(s -> s.getClasses().stream()); int count = stream.count();