Sub topic 11
Combining Elements with reduce
Sometimes you want one answer from many values, such as a total, the largest number, or one long word made from many short ones. The reduce operation gives you that answer. Reduction means combining all the elements of a stream into a single value.
How reduce Works
reduce is a terminal operation. A terminal operation ends the pipeline and produces a result. The most common form takes two arguments:
- Identity: the starting value. It is also the result if the stream is empty. For a sum, the identity is
0, because adding0changes nothing. - Accumulator: a function that takes two values and returns one. It combines the running result with the next element.
reduce starts with the identity. It then combines that value with the first element, combines the result with the second element, and keeps going until no elements are left.
A Worked Example
This program finds the sum and the largest value in a list:
import java.util.List;
public class ReduceExample {
public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3, 4, 5);
int sum = numbers.stream().reduce(0, Integer::sum);
int max = numbers.stream().reduce(Integer.MIN_VALUE, Integer::max);
System.out.println(sum); // 15
System.out.println(max); // 5
}
}Integer::sum is a method reference. It works the same as the lambda (a, b) -> a + b. For the maximum, the identity is Integer.MIN_VALUE, the smallest possible int. Any real number in the list is at least as big as it.
Notice that the code makes a new stream for each reduce call. A stream can be used only once.
reduce Without an Identity
You can also call reduce with only the accumulator. With no starting value, an empty stream has no answer, so this form returns an Optional. An Optional is a box that may or may not hold a value.
import java.util.List;
import java.util.Optional;
public class ReduceOptional {
public static void main(String[] args) {
List<Integer> empty = List.of();
Optional<Integer> max = empty.stream().reduce(Integer::max);
System.out.println(max.orElse(-1)); // -1
}
}Choosing a Good Accumulator
For common tasks, Java offers shortcuts. count() counts elements. Primitive streams such as IntStream have sum(), max(), and min(), which a later chapter covers. Use reduce when no shortcut fits.
Exercise
Write one line that uses reduce to multiply all numbers in List.of(2, 3, 4). What identity value should you use, and what is the result?
Show answer
Use numbers.stream().reduce(1, (a, b) -> a * b). The identity is 1, because multiplying by 1 changes nothing. The result is 24.
Exercise
Why does numbers.stream().reduce(Integer::max) return an Optional<Integer> instead of an Integer?
Show answer
Without an identity value, an empty stream has nothing to return. The Optional lets the result be empty in that case.