Java Stream API – 计算嵌套列表的项目

假设我们有一个国家List列表: List并且每个国家/地区都有对其区域列表的引用: List (例如,美国的情况)。 像这样的东西:

 USA Alabama Alaska Arizona ... Germany Baden-Württemberg Bavaria Brandenburg ... 

在“普通的”Java中,我们可以计算所有区域,例如:

 List countries = ... int regionsCount = 0; for (Country country : countries) { if (country.getRegions() != null) { regionsCount += country.getRegions().size(); } } 

是否有可能通过Java 8 Stream API实现相同的目标? 我想到了类似的东西,但我不知道如何使用流API的count()方法count()嵌套列表的项目:

 countries.stream().filter(country -> country.getRegions() != null).??? 

您可以使用map()获取区域列表Stream ,然后使用mapToInt获取每个国家/地区的区域数量。 之后使用sum()来获取IntStream中所有值的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(); 

注意:在过滤之前使用getRegions的好处是您不需要多次调用getRegions

您可以将每个国家/地区映射到区域数量,然后使用sum减少结果:

 countries.stream() .map(c -> c.getRegions() == null ? 0 : c.getRegions().size()) .reduce(0, Integer::sum); 

你甚至可以使用flatMap()

 countries.stream().map(Country::getRegions).flatMap(List::stream).count(); where, map(Country::getRegions) = returns a Stream> flatMap(List::stream) = returns a Stream