I have a stream of Integers and the source of the stream is a list: [3, 27]
.
When doing list.stream.reduce(1, (a,b) -> a/b))
, how do I get the reduce to divide 3/1 = 3 then 27/3 = 9 and return 9?
This Stream method is a terminal operation which performs reduction on the given stream and returns a reduced (or single) value reduce () method helps to derive sum of the Stream, searching max/mix element amongst Stream elements or finding average and performing String concatenation 2. Stream reduce () method with accumulator :
What is ‘reducing’ in the context of Streams. Reducing in the context of Java 8 Streams refers to the process of combining all elements in the stream repeatedly to produce a single value which is returned as the result of the reduction operation.
Java stream reduce example with identity, accumulator and combiner: One more variant of Java stream reduce is available. It takes one third parameter called combiner. The first parameter is the identity, and the second one is the accumulator. The combiner is like an accumulator.
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.
One should not use reduce
with an accumulator function that is not associative. This has been especially highlighted in the JDK documentation of the API as well.
The accumulator function must be an associative function.
You don't really need to rely on streams for this manipulation, in fact, streams are not good in persisting intermediate states(as in this case), so a simple for loop solution shall work for you :
int reduce = 1;
for (Integer integer : List.of(3, 27)) {
reduce = integer / reduce;
}
System.out.println(reduce);
To test out the inconsistency in terms of using the stream API for this purpose, just change your code to the following and notice the output!
Integer reduce = List.of(3, 7).parallelStream().reduce(1, (a, b) -> b / a);
System.out.println(reduce);
You have to swap a and b:
System.out.println (Stream.of(3,27).reduce(1, (a,b) -> b/a));
output:
9
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With