繁体   English   中英

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

[英]Java Stream API - count items of a nested list

假设我们有一个国家List<Country>List<Country> ,每个国家都有对其区域列表的引用: List<Region> (例如美国的州)。 像这样的东西:

USA
  Alabama
  Alaska
  Arizona
  ...

Germany
  Baden-Württemberg
  Bavaria
  Brandenburg
  ...

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

List<Country> 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<List<Regions>>
flatMap(List::stream) = returns a Stream<Regions>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM