Java Stream API - count items of a nested list(Java Stream API - 计算嵌套列表的项目)
问题描述
假设我们有一个国家/地区列表:List,每个国家/地区都有一个对其区域列表的引用:List(例如以美国为例).像这样的:
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
...
在普通"Java 中,我们可以计算所有区域,例如这样:
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();
}
}
是否可以使用 Java 8 Stream API 实现相同的目标?我想过类似的事情,但我不知道如何使用流 API 的 count() 方法计算嵌套列表的项目:
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).???
推荐答案
您可以使用 map() 来获取区域列表的 Stream,然后 mapToInt 获取每个国家/地区的区域数.之后使用 sum() 获取 IntStream 中所有值的总和:
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();
注意:在过滤之前使用getRegions的好处是你不需要多次调用getRegions.
Note: The benefit of using getRegions before filtering is that you don't need to call getRegions more than once.
这篇关于Java Stream API - 计算嵌套列表的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java Stream API - 计算嵌套列表的项目
基础教程推荐
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
