我很难完全理解combiner
在Streams reduce
方法中所扮演的角色。
例如,以下代码无法编译:
int length = asList("str1", "str2").stream()
.reduce(0, (accumulatedInt, str) -> accumulatedInt + str.length());
编译错误显示:(参数不匹配;int不能转换为java.lang.String)
但是下面的代码可以编译:
int length = asList("str1", "str2").stream()
.reduce(0, (accumulatedInt, str ) -> accumulatedInt + str.length(),
(accumulatedInt, accumulatedInt2) -> accumulatedInt + accumulatedInt2);
我知道组合器方法是在并行流中使用的-所以在我的示例中,它将两个中间累加整数相加在一起。
但我不明白为什么第一个示例不能在没有组合器的情况下编译,也不明白组合器是如何解决string到int的转换的,因为它只是将两个int相加在一起。
有人能说明这一点吗?
https://stackoverflow.com/questions/24308146
复制相似问题