使用Lambda计数列表中的列表

Sel*_*lbi 4 java

我有一些对象的列表,每个对象进一步包含另一个列表,我想计算这些嵌套列表中所有项目的总数。我现在是这样的:

int accu = 0;
for (SomeObject so : objects) {
    accu += so.getListWithinObject().size();
}
Run Code Online (Sandbox Code Playgroud)

但是我觉得这可以使用Java 8魔术写成一行。也许甚至都不困难,我只是不知道怎么做。

And*_*rea 6

如果它只是一个两层结构(因此,内部对象不包含您要求和的其他列表),则可以这样做:

objects.stream().map(SomeObject ::getListWithinObject)
       .filter(Objects::nonNull)
       .mapToInt(List::size)
       .sum();
Run Code Online (Sandbox Code Playgroud)

  • 为什么没有完整的过滤器?这似乎不是原始代码的一部分。 (2认同)

Mus*_*waz 6

我将列出四个单线。每个给定相同的输出:

  1. objects.stream().map(SomeObject::getListWithinObject).flatMap(List::stream).count();

  2. objects.stream().flatMap(e -> e.getListWithinObject().stream()).count();

  3. objects.stream().map(e -> e.getListWithinObject().size()).reduce(0, Integer::sum);

  4. objects.stream().mapToLong(e -> e.getListWithinObject().size()).sum();

我敢肯定,还有其他方法。它仅显示了Stream API的强大功能。您可以通过多种方式执行一项任务。

厄立特里亚提供了另外两个单线(在评论中)而未使用映射

  1. objects.stream().collect(Collectors.summingInt(so -> so.getListWithinObject().size()));

  2. objects.stream().reduce(0, (subSum, so) -> subSum + so.getListWithinObject().size(), Integer::sum)