The Stream.reduce()
method combines a sequence of elements into a single element. It achieves this by applying a reduction operation, which is to apply a binary operator on each element in the sequence to reduce it to a single value.
We can also use Stream.reduce()
method with parallel streams to perform a parallel reduction operation.
Following is the syntax of the Stream.reduce()
method:
T reduce(T identity, BinaryOperator<T> accumulator)
Here, T
is the type of element in the Stream
and the return type is also of the same type T
.
identity
: This is the identity element. It is returned when the stream is empty.accumulator
: This is a function that accepts two arguments and produces a single value. It acts as an accumulator for the reduction operation.This method returns the reduction result as an object of type T
.
In the code example below, we have a sequence of integers as input. To sum them up, we can use the Stream.reduce()
method.
import java.util.*;class Main {public static void main( String args[] ) {List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);int sum = numbers.stream().reduce(0, (a, b) -> a + b);System.out.println("Sum of all numbers: " + sum);}}
reduce()
method to sum them up. The first argument for the reduce()
method is the starting value (in this case, 0
). The second argument is a binary operator that takes two operands and returns a single value (in this case, +
).