BinaryOperator
Computes a single value from two values of the same type.
Among other uses, employed in multiple overloads of Stream
.reduce
to combine pairs of values in the stream, ultimately resulting in producing a single value.
The method to be implemented is T apply(T t1, T t2)
; a lambda implementation must therefore take 2 parameters of type T
and return a value of type T
. (This is a subinterface of BiFunction
<T,U,R>
; the apply
method of that interface takes 2 parameters, of types T
and U
, respectively, and returns a result of type R
.)
String
using Stream
.reduce(
BinaryOperator
)
:String source = "The quick brown fox jumps over the lazy dog.";
Pattern delimiter = Pattern.compile("\\W+"); // Matches non-word characters.
delimiter.splitAsStream(source) // Split on non-word characters.
.filter((s) -> !s.isEmpty()) // Filter out empty strings.
.map(String::toLowerCase) // Map each string to lower-case.
.reduce((s1, s2) -> s1 + "-" + s2) // Concatenate into slug.
.ifPresent(System.out::println); // Print the value.
This example splits a String
into a Stream
<String>
using a regular expression Pattern
. Then, empty items are filtered out (using a Predicate
<String>
lambda) and the remaining values are converted to lower-case (using a Function
<String, String>
lambda). Finally, the Stream
<String>
contents are reduced to an Optional<String>
using a BinaryOperator
<String>
lambda, and the contents of the Optional<String>
are printed using a Consumer
<String>
lambda (expressed with method reference syntax). This produces the output
the-quick-brown-fox-jumps-over-the-lazy-dog
(Note: A joining collector could have produced the same result as the reduce operation in the above example; see the Stream
.sorted(
Comparator
)
example, below, for an illustration.)