举个例子,我有一个列表(或集合),其中的每个条目都需要执行相同的方法。对于这样的兰巴来说,这是非常容易的:
ingredientBaskets.forEach(this::processToMarmalade);
但是,我希望 processToMarmalade 方法返回无法处理的水果 block 的数量,并最终将其汇总。我可以通过让方法求和并返回错误数来轻松做到这一点。
我想要的基本上是这样的:
int result = ingredientBaskets.forEach(this::processToMarmalade).sum();
一些东西。 或者换句话说,具有与此相同的功能:
int result = 0;
for (final Basket basket: ingredientBaskets) {
result += processToMarmalade(basket)
}
}
有办法做到这一点吗?
编辑:从答案来看,List 和 Set 将允许使用 IntStream,这是我需要的一件事。但是,如果它是可迭代的怎么办?这个没有流,只有 forEach。
假设原来的问题,也是针对 Iterable 的情况。 forEach 可以以某种方式总结所有内容,还是我必须创建一个新列表并首先用 Iterable 的内容填充它?
最佳答案
您正在寻找的是the mapToInt
method (假设 processToMarmalade
返回 int
):
int result = ingredientBaskets.stream().mapToInt(this::processToMarmalade).sum();
如果ingredientBaskets
你有一个 Iterable<?>
,您可以convert it to a stream像这样:
StreamSupport.stream(ingredientBaskets.spliterator(), false)
.mapToInt(this::processToMarmalade)
.sum();
关于Java 8 lambda 表达式 : Summing up method return values in a for each call for List/Set and Iterable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47093463/