How to count items of nested lists?

Viewed 2978

How can I use the Stream API to count items of nested lists?

Imagine 3 nested lists:

List<OuterList> outerLists;

class OuterList {
    List<Sublist> subLists;
}

class Sublist {
    List<String> items;
}

I just want to sum the number of items.size() of all lists. I'm trying to achive something like:

outerLists.stream().forEach(outer -> 
  outer.getSubLists().stream().forEach(sub -> 
  sub.getItems().size())
 .sum/count()?
2 Answers
Related