Let\'s assume that we have a list of countries: List
and each country has a reference to a list of its regions: List
You may map each country to number of regions and then reduce result using sum:
countries.stream()
.map(c -> c.getRegions() == null ? 0 : c.getRegions().size())
.reduce(0, Integer::sum);
You could use map()
to get a Stream
of region lists and then mapToInt to get the number of regions for each country. After that use sum() to get the sum of all the values in the IntStream
:
countries.stream().map(Country::getRegions) // now it's a stream of regions
.filter(rs -> rs != null) // remove regions lists that are null
.mapToInt(List::size) // stream of list sizes
.sum();
Note: The benefit of using getRegions
before filtering is that you don't need to call getRegions
more than once.
You could even use flatMap()
like:
countries.stream().map(Country::getRegions).flatMap(List::stream).count();
where,
map(Country::getRegions) = returns a Stream<List<Regions>>
flatMap(List::stream) = returns a Stream<Regions>