Stream.reduce()
Folds all stream elements into a single value.
Available since: Java 8
Syntax
T reduce(T identity, BinaryOperator<T> accumulator)
Optional<T> reduce(BinaryOperator<T> accumulator)Parameters
| Parameter | Type | Description |
|---|---|---|
| identity | T | The starting value (0 for a sum, 1 for a product). |
| accumulator | BinaryOperator<T> | Combines the accumulated result with the next element. |
Return value
T | Optional<T>The final value; without a starting value — an `Optional`.
Examples
A sum and a product:
void main() {
List<Integer> nums = List.of(1, 2, 3, 4);
IO.println(nums.stream().reduce(0, Integer::sum));
IO.println(nums.stream().reduce(1, (a, b) -> a * b));
}Output:
10
24Without a starting value the result is an Optional:
void main() {
Optional<String> longest = Stream.of("pear", "banana", "fig")
.reduce((a, b) -> a.length() >= b.length() ? a : b);
IO.println(longest.orElse("none"));
IO.println(Stream.<String>empty().reduce((a, b) -> a + b).isPresent());
}Output:
banana
falseNotes
For common cases there are ready-made methods that read better: mapToInt(...).sum(), count(), max(), Collectors.joining(). The starting value must be neutral: 0 for addition, 1 for multiplication, "" for string concatenation.
See also
- IntStream.sum() — Adds up all numbers of a stream.
- Stream.count() — Counts the elements of a stream.
- BinaryOperator — A two-argument function whose arguments and result share a type.
In the tutorial
- Stream operations — The main Stream API operations — filter, map, sorted, distinct, limit, skip, count, reduce, anyMatch, findFirst and numeric streams.