TransWikia.com

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

Stack Overflow Asked by Shrinath Shankar on August 21, 2020

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?

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);

Answered by Naman on August 21, 2020

You have to swap a and b:

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

output:

9

Answered by Eran on August 21, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP