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.
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
- Java.util.LinkedList.poll(), pollFirst(), pollLast() with examples in Java
- Java.lang.Short toString() method in Java with Examples
- Java.util.function.LongPredicate interface in Java with Examples
- Java.util.function.IntPredicate interface in Java with Examples
- Java lang.Long.reverse() method in Java with Examples
- Java lang.Long.builtcount() method in Java with Examples
- Java lang.Long.byteValue() method in Java with Examples
- Java lang.Long.numberOfLeadingZeros() method in Java with Examples
- Java lang.Long.lowestOneBit() method in Java with Examples
- Java lang.Long.numberOfTrailingZeros() method in Java with Examples
- Java.util.Collections.rotate() Method in Java with Examples
- Java lang.Long.highestOneBit() method in Java with Examples
- Java.util.concurrent.Phaser class in Java with Examples
- Java.util.concurrent.RecursiveAction class in Java with Examples
- Java.util.Collections.disjoint() Method in java with Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.