i am currently reading the O'reilly
Java 8 Lambdas is a really good book. i came across with a example like this.
i have a
private final BiFunction<StringBuilder,String,StringBuilder>accumulator=
(builder,name)->{if(builder.length()>0)builder.append(",");builder.append("Mister:").append(name);return builder;};
final Stream<String>stringStream = Stream.of("John Lennon","Paul Mccartney"
,"George Harrison","Ringo Starr");
final StringBuilder reduce = stringStream
.filter(a->a!=null)
.reduce(new StringBuilder(),accumulator,(left,right)->left.append(right));
System.out.println(reduce);
System.out.println(reduce.length());
this produce the right output.
Mister:John Lennon,Mister:Paul Mccartney,Mister:George Harrison,Mister:Ringo Starr
my question is regarded the reduce
method the last parameter which is a BinaryOperator
my question is which this parameter is used for? if i change by
.reduce(new StringBuilder(),accumulator,(left,right)->new StringBuilder());
the ouput is the same if i pass NULL
then N.P.E is returned.
what for this parameter is used for?
UPDATE
why if i run it on parallelStream
i am receiving differents results?
first run.
returned StringBuilder length = 420
second run
returned StringBuilder length = 546
third run
returned StringBuilder length = 348
and so on? why is this... should not return all the values at each iteration?
any help is hugely grateful.
thanks.