membersound
membersound

Reputation: 86925

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

Upvotes: 4

Views: 3781

Answers (2)

Tunaki
Tunaki

Reputation: 137289

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

Upvotes: 9

Eran
Eran

Reputation: 394126

You can use flatMap to convert a Stream<OuterList> to a Stream<Sublist> and then to a Stream<String> of all the Strings in all the innermost lists :

outerLists.stream()
          .flatMap(ol -> ol.subLists().stream())
          .flatMap(s->s.items.stream()).count();

However, if there are duplicates, they will be counted multiple times.

Upvotes: 4

Related Questions