Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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

ParameterTypeDescription
identityTThe starting value (0 for a sum, 1 for a product).
accumulatorBinaryOperator<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
24

Without 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
false

Notes

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

In the tutorial

  • Stream operations — The main Stream API operations — filter, map, sorted, distinct, limit, skip, count, reduce, anyMatch, findFirst and numeric streams.

Thanks for reading!

Donate to the site — we work hard for you.