Stream.reduce() in Java with examples
Many times, we need to perform operations where a stream reduces to single resultant value, for example, maximum, minimum, sum, product, etc. Reducing is the repeated process of combining all elements.
reduce operation applies a binary operator to each element in the stream where the first argument to the operator is the return value of the previous application and second argument is the current stream element.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
T reduce(T identity, BinaryOperator<T> accumulator); Where, identity is initial value of type T and accumulator is a function for combining two values.
sum(), min(), max(), count() etc. are some examples of reduce operations. reduce() explicitly asks you to specify how to reduce the data that made it through the stream.
Let us see some examples to understand the reduce() function in a better way :
Example 1 :
Example 2 :
Example 3 :
The sum of all elements is 16
Example 4 :
The product is : 5040