Trevor Trevor - 1 year ago 81
Java Question

I want to count the number of Collections in a Collection, in a Collection with Streams

Let's say I have a

, that has many
, that has many
that have many

I want to count the number of classes given a SchoolDistrict.

The Java 7 way would be like so:

Integer classCount = 0;
for (School school : schoolDistrict)
for (Student student : school.getStudents())
classCount += student.getClasses().size();

I know that Java 8 brings streams that are supposed to make this kind of thing a bit easier on the eyes.

But I'm having trouble figuring out how to do it.

Any takers?

EDIT: someone marked this as a duplicate of this post, I don't believe it is as that example only went 2 levels deep (Countries to Regions). My question relates to a problem that goes four levels deep (SchoolDistricts to Schools to Students to Classes)

Answer Source

You can use -> 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 mapToInt() and sum() as the end operation.

So flatMap() is the secret to unnesting or "flattening" nested collections.

Stream<MyClass> stream = -> s.getStudents().stream()).flatMap(s -> s.getClasses().stream());
int count = stream.count();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download