What is the Stream.reduce() method in Java?
Overview
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.
Syntax
Following is the syntax of the Stream.reduce() method:
T reduce(T identity, BinaryOperator<T> accumulator)
The syntax of Stream.reduce()
Here, T is the type of element in the Stream and the return type is also of the same type T.
Parameters
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.
Return value
This method returns the reduction result as an object of type T.
Code example
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);}}
Explanation
- Line 5: We create a list of integers.
- Lines 6–7: We use the
reduce()method to sum them up. The first argument for thereduce()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,+).