我正在学习 Java 8。我要面对的最困难的事情是 Parallel Reduction。这是我正在研究的用户@Stuart Marks 的示例代码。
class ImmutableAverager
{
private final int total;
private final int count;
public ImmutableAverager(){this.total = 0;this.count = 0;}
public ImmutableAverager(int total, int count)
{
this.total = total;
this.count = count;
}
public double average(){return count > 0 ? ((double) total) / count : 0;}
public ImmutableAverager accept(final int i)
{
return new ImmutableAverager(total + i, count + 1);
}
public ImmutableAverager combine(final ImmutableAverager other)
{
return new ImmutableAverager(total + other.total, count + other.count);
}
通话
public static void main(String[] args)
{
System.out.println(Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
.parallel()
.reduce(new ImmutableAverager(),
ImmutableAverager::accept,
ImmutableAverager::combine)
.average());
}
这会产生正确的结果,但后来我检查了 reduce 方法的签名
<U> U reduce(U identity,
BiFunction<U, ? super T, U> accumulator,
BinaryOperator<U> combiner);
如果代码类似于:
.reduce(new ImmutableAverager(),(a,b)->a.accept(b),(a,b)->a.combine(b))
我不明白如何:
ImmutableAverager::accept
可以转换成BiFunction
我的理解是这样的:
ImmutableAverager::accept
是把它转换成类似的东西
(ImmutableAverage a)->a.accept(); //but this is a function with 1 parameter not with 2 parameters.
和
ImmutableAverager::merge
可以转换成BinaryOperator
. 我的朋友@Stuart Marks 说
这些方法匹配函数参数以减少,因此我们可以使用方法引用。