Functional Interfaces: BinaryOperator

Computes a single value from two values of the same type.

Overview

Example

Sluggify 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.)