Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count items of nested lists?

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()?
like image 530
membersound Avatar asked Dec 19 '22 18:12

membersound


1 Answers

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().

like image 103
Tunaki Avatar answered Dec 21 '22 10:12

Tunaki