I try to understand how reduce()
method works exactly with parallel streams and I don't understand why the following code do not return the concatenation of these strings.
This is the code:
public class App {
public static void main(String[] args) {
String[] grades = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"};
StringBuilder concat = Arrays.stream(grades).parallel()
.reduce(new StringBuilder(),
(sb, s) -> sb.append(s),
(sb1, sb2) -> sb1.append(sb2));
System.out.println(concat);
}
}
The code works only with sequential streams, but with parallel streams it doesn't return the concatenation. The output is different every time. Can someone explain me what's happening there?
reduce
like it's a mutable one, and it's not. hint:accumulator
andcombiner
must return a new instance ofStringBuilder
, all the time. – Mirella