Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get `reduce` to divide values in the stream by one another?

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?

like image 537
Shrinath Shankar Avatar asked Jul 20 '20 05:07

Shrinath Shankar


People also ask

What is the use of stream reduce() method in Java?

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?

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.

What is combiner in Java stream reduce?

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.

When do we need to perform operations where a stream reduces?

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.


2 Answers

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);
like image 132
Naman Avatar answered Oct 12 '22 23:10

Naman


You have to swap a and b:

System.out.println (Stream.of(3,27).reduce(1, (a,b) -> b/a));

output:

9
like image 22
Eran Avatar answered Oct 12 '22 23:10

Eran