IntStream reduce(IntBinaryOperator op) in Java with Examples
IntStream reduce(IntBinaryOperator op) performs a reduction on the elements of this stream, using an associative accumulation function, and returns an OptionalInt describing the reduced value, if any.
A reduction operation or fold takes a sequence of input elements and combines them into a single summary result, such as finding the sum or maximum of a set of numbers. An operator or function op is associative if the following holds :
(a op b) op c == a op (b op c)
This is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect. After the terminal operation is performed, the stream pipeline is considered consumed, and can no longer be used.
Syntax :
OptionalInt reduce(IntBinaryOperator op)
Parameters :
- OptionalInt : A container object which may or may not contain a int value. If a value is present, isPresent() will return true and getAsInt() will return the value.
- IntBinaryOperator : An operation upon two int-valued operands and producing an int-valued result.
- op : An associative, stateless function for combining two values.
Return Value : An OptionalInt describing the reduced value, if any.
Example 1 :
// Java code for IntStream reduce // (IntBinaryOperator op) import java.util.OptionalInt; import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream IntStream stream = IntStream.of( 2 , 3 , 4 , 5 , 6 ); // Using OptionalInt (a container object which // may or may not contain a non-null value) // Using IntStream reduce(IntBinaryOperator op) OptionalInt answer = stream.reduce(Integer::sum); // if the stream is empty, an empty // OptionalInt is returned. if (answer.isPresent()) { System.out.println(answer.getAsInt()); } else { System.out.println( "no value" ); } } } |
Output :
20
Example 2 :
// Java code for IntStream reduce // (IntBinaryOperator op) import java.util.OptionalInt; import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream IntStream stream = IntStream.of( 2 , 3 , 4 , 5 , 6 ); // Using OptionalInt (a container object which // may or may not contain a non-null value) // Using IntStream reduce(IntBinaryOperator op) OptionalInt answer = stream.reduce((a, b) -> (a * b)); // if the stream is empty, an empty // OptionalInt is returned. if (answer.isPresent()) { System.out.println(answer.getAsInt()); } else { System.out.println( "no value" ); } } } |
Output :
720