What is the equivalent of of Scala's great foldLeft
in Java 8?
I was tempted to think it was reduce
, but reduce has to return something of identical type to what it reduces on.
Example:
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();
}
}
The problem in the code above is the acc
umulator: new StringBuilder("")
Thus, could anyone point me to the proper equivalent of the foldLeft
/fix my code?