我有一些对象的列表,每个对象进一步包含另一个列表,我想计算这些嵌套列表中所有项目的总数。我现在是这样的:
int accu = 0;
for (SomeObject so : objects) {
accu += so.getListWithinObject().size();
}
Run Code Online (Sandbox Code Playgroud)
但是我觉得这可以使用Java 8魔术写成一行。也许甚至都不困难,我只是不知道怎么做。
如果它只是一个两层结构(因此,内部对象不包含您要求和的其他列表),则可以这样做:
objects.stream().map(SomeObject ::getListWithinObject)
.filter(Objects::nonNull)
.mapToInt(List::size)
.sum();
Run Code Online (Sandbox Code Playgroud)
我将列出四个单线。每个给定相同的输出:
objects.stream().map(SomeObject::getListWithinObject).flatMap(List::stream).count();
objects.stream().flatMap(e -> e.getListWithinObject().stream()).count();
objects.stream().map(e -> e.getListWithinObject().size()).reduce(0, Integer::sum);
objects.stream().mapToLong(e -> e.getListWithinObject().size()).sum();
我敢肯定,还有其他方法。它仅显示了Stream API的强大功能。您可以通过多种方式执行一项任务。
厄立特里亚提供了另外两个单线(在评论中)而未使用映射:
objects.stream().collect(Collectors.summingInt(so -> so.getListWithinObject().size()));
objects.stream().reduce(0, (subSum, so) -> subSum + so.getListWithinObject().size(), Integer::sum)
| 归档时间: |
|
| 查看次数: |
153 次 |
| 最近记录: |