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()?
You can use flatMapToInt
:
outerLists.stream()
.flatMapToInt(outer ->
outer.subLists.stream().mapToInt(sub -> sub.items.size())
)
.sum();
This will be more performant than flat mapping the whole sublists since here, we're just mapping each sublist into the size of its items. The idea here is that the Stream<OuterList>
is flat mapped into an IntStream
where each outer is replaced to a stream made of the size of all its inner lists. Then, we sum the values with sum()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With