Let's assume that we have a list of countries: List<Country>
and each country has a reference to a list of its regions: List<Region>
(e.g. states in the case of the USA). Something like this:
USA
Alabama
Alaska
Arizona
...
Germany
Baden-Württemberg
Bavaria
Brandenburg
...
In "plain-old" Java we can count all regions e.g. this way:
List<Country> countries = ...
int regionsCount = 0;
for (Country country : countries) {
if (country.getRegions() != null) {
regionsCount += country.getRegions().size();
}
}
Is it possible to achieve the same goal with Java 8 Stream API? I thought about something similar to this, but I don't know how to count items of nested lists using count()
method of stream API:
countries.stream().filter(country -> country.getRegions() != null).???
List::size
is anO(1)
operation whilst using aflatMap
on every list is anO(n)
operation.