我无法完全理解combinerStreams reduce方法中实现的角色.
例如,以下代码不编译:
int length = asList("str1", "str2").stream()
.reduce(0, (accumulatedInt, str) -> accumulatedInt + str.length());
Run Code Online (Sandbox Code Playgroud)
编译错误说:( 参数不匹配; int无法转换为java.lang.String)
但是这段代码确实编译:
int length = asList("str1", "str2").stream()
.reduce(0, (accumulatedInt, str ) -> accumulatedInt + str.length(),
(accumulatedInt, accumulatedInt2) -> accumulatedInt + accumulatedInt2);
Run Code Online (Sandbox Code Playgroud)
我知道组合器方法用于并行流 - 所以在我的例子中它将两个中间累积的int加在一起.
但是我不明白为什么第一个例子在没有组合器的情况下编译或者组合器如何解决字符串到int的转换,因为它只是将两个整数加在一起.
任何人都可以阐明这一点吗?
Scala foldLeft在Java 8中的优势是什么?
我很想想它reduce,但是减少必须返回与它减少的相同类型的东西.
例:
import java.util.List;
public class Foo {
// this method works pretty well
public int sum(List<Integer> numbers) {
return numbers.stream()
.reduce(0, (acc, n) -> (acc + n));
}
// this method makes the file not compile
public String concatenate(List<Character> chars) {
return chars.stream()
.reduce(new StringBuilder(""), (acc, c) -> acc.append(c)).toString();
}
}
Run Code Online (Sandbox Code Playgroud)
上面代码中的问题是accumulator:new StringBuilder("")
因此,任何人都可以指出我正确的foldLeft/修复我的代码?