Java Stream API - 计算嵌套列表的项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33317862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Stream API - count items of a nested list
提问by dominik
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:
让我们假设我们有一个国家/List<Country>
地区列表:每个国家/地区都有对其地区列表的引用:(List<Region>
例如美国的州)。像这样的东西:
USA
Alabama
Alaska
Arizona
...
Germany
Baden-Württemberg
Bavaria
Brandenburg
...
In "plain-old" Java we can count all regions e.g. this way:
在“普通”Java 中,我们可以计算所有区域,例如这样:
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:
是否可以使用 Java 8 Stream API 实现相同的目标?我想过类似的事情,但我不知道如何使用count()
流 API 的方法计算嵌套列表的项目:
countries.stream().filter(country -> country.getRegions() != null).???
回答by fabian
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
:
您可以使用map()
获取Stream
区域列表,然后mapToInt
获取每个国家/地区的区域数量。之后使用sum()
获取 中所有值的总和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.
注意:getRegions
在过滤之前使用的好处是您不需要getRegions
多次调用。
回答by Vasily Liaskovsky
You may map each country to number of regions and then reduce result using sum:
您可以将每个国家映射到区域数量,然后使用 sum 减少结果:
countries.stream()
.map(c -> c.getRegions() == null ? 0 : c.getRegions().size())
.reduce(0, Integer::sum);
回答by Ram Patra
You could even use flatMap()
like:
你甚至可以使用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>