The question is straight forward: Why can't we use StringBuilder(...)
as identity function
in the reduce(...)
operations in the java8
streams, but string1.concat(string2)
can be used as the identity function
?
string1.concat(string2)
can be seen as similar to builder.append(string)
(though it is understood that there are few differences in these opeations), but I am not able to understand the difference in the reduce operation. Consider the following example:
List<String> list = Arrays.asList("1", "2", "3");
// Example using the string concatenation operation
System.out.println(list.stream().parallel()
.reduce("", (s1, s2) -> s1 + s2, (s1, s2)->s1 + s2));
// The same example, using the StringBuilder
System.out.println(list.stream() .parallel()
.reduce(new StringBuilder(""), (builder, s) -> builder
.append(s),(builder1, builder2) -> builder1
.append(builder2)));
// using the actual concat(...) method
System.out.println(list.stream().parallel()
.reduce("", (s1, s2) -> s1.concat(s2), (s1, s2)->s1.concat(s2)));
Here is the output after executing above lines:
123
321321321321 // output when StringBuilder() is used as Identity
123
builder.append(string)
is an associative operation as str1.concat(str2)
is. Then why does concat
work and append
doesn't?