Java 8 shortens BinaryOperator, what is it used for?

I am currently reading O'reilly Java 8 Lambdas - a really good book. I came across such an example.

i has

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 leads to the correct exit.

Mister:John Lennon,Mister:Paul Mccartney,Mister:George Harrison,Mister:Ringo Starr

my question is considered the reducelast parameter method which isBinaryOperator

I have a question for which this parameter is used? if i change to

.reduce(new StringBuilder(),accumulator,(left,right)->new StringBuilder());

the output will be the same, if I pass NULL, then NPE returns

what is this parameter used for?

UPDATE

why, if I ran it on parallelStream, do I get difference results?

first start.

returned StringBuilder length = 420

second launch

returned StringBuilder length = 546

third launch

returned StringBuilder length = 348

etc? why does this ... not have to return all values ​​at each iteration?

any help is greatly appreciated.

thank.

+4
2

reduce Stream . :

combiner . -, . . , , :

Stream<String>stringStream = Stream.of(
    "John Lennon", "Paul Mccartney", "George Harrison", "Ringo Starr")
    .parallel();

, combiner , . String acc accumulator.apply. :

acc(acc(acc(acc(identity, "one"), "two"), "three"), "four");

combiner . .

combiner.apply(
    acc(acc(identity, "one"), "two"),
    acc(acc(identity, "three"), "four"));

, accumulator :

BiFunction<StringBuilder,String,StringBuilder> accumulator =
    (builder,name) -> builder.append(name);

Javadoc Stream:: , accumulator . , :

acc(acc(acc(identity, "one"), "two"), "three")  
acc(acc(identity, "one"), acc(acc(identity, "two"), "three"))

accumulator. , , identity. reduce. , :

// identity = ""
BiFunction<String,String,String> accumulator = String::concat;

// identity = null
BiFunction<StringBuilder,String,StringBuilder> accumulator =
    (builder,name) -> builder == null
        ? new StringBulder(name) : builder.append(name);
+12

nosid answer (+1), .

identity reduce . , , , . "identity" , ! . .

, 5-19 , Java 8 Lambdas, O'Reilly 2014. , .

+3

Source: https://habr.com/ru/post/1542832/


All Articles