Course contentsShow
← Java
Lesson 1686 of 2,87035. Functional InterfacesFree lesson

Using BinaryOperator for Reduction Operations

Apply BinaryOperator with reduce to combine elements, such as summing integers or concatenating strings.

Using BinaryOperator for Reduction Operations

You'll learn how to use BinaryOperator with reduction methods to combine stream elements into a single result.

The Core Idea

A BinaryOperator<T> takes two values of the same type and produces one result of that same type. This makes it perfect for reduction operations—repeatedly combining elements until you have a single value. Think of it like folding a long chain: you take two links, combine them, then combine that result with the next link, and so on until you have one final piece.

The most common use case is with the reduce method on streams, which applies your BinaryOperator to accumulate elements into a final result.

Common Reduction Patterns

Summing Integers

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

BinaryOperator<Integer> sum = (a, b) -> a + b;
int total = numbers.stream()
                   .reduce(0, sum);  // Result: 15

The reduction starts with 0, then combines: 0+1=1, then 1+2=3, then 3+3=6, and so on.

Concatenating Strings

List<String> words = Arrays.asList("Java", "is", "powerful");

BinaryOperator<String> concat = (s1, s2) -> s1 + " " + s2;
String sentence = words.stream()
                       .reduce("", concat);  // Result: " Java is powerful"

Finding Maximum

List<Integer> values = Arrays.asList(5, 12, 3, 19, 7);

BinaryOperator<Integer> max = (a, b) -> a > b ? a : b;
int largest = values.stream()
                    .reduce(Integer.MIN_VALUE, max);  // Result: 19

The Reduction Process

With reduce(identity, binaryOperator), the operation flows like: identity ⊕ element1 ⊕ element2 ⊕ ... where ⊕ is your BinaryOperator.

Key Takeaway: BinaryOperator is the natural choice for reduction operations because it takes two values of type T and returns a combined T, making it perfect for accumulating stream elements into a single result.