Scala中很棒的foldLeft
在Java 8中有什么等价物吗?
我曾经认为答案是reduce
,但是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();
}
}
上面代码中的问题在于累加器:new StringBuilder("")
因此,有没有人能够指点我正确的等价于foldLeft
的方法或者修复我的代码?