AnswerBun.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!

Related Questions

Laravel Slow queries

5  Asked on November 7, 2021 by squiggs

     

Display image that returns HTTP 503 in Firefox

2  Asked on November 7, 2021 by brainstone

       

Simple TCP listener on swift

1  Asked on November 7, 2021 by mr-park

       

check the type of the only child in react

1  Asked on November 7, 2021

 

Cannot update document using the NodeJS MongoDB driver

1  Asked on November 7, 2021 by niaz-m-sameer

   

Can not convert umlauts (Ü Ö Ä ü ö ä è é) to .utf8

2  Asked on November 7, 2021 by salome-tsiramua

       

elegant way of extracting option value when need it

1  Asked on November 7, 2021 by user804968

 

Sign PDF asynchronous using PDFBox

0  Asked on November 7, 2021 by lawrence-leung

         

Get non hidden element with previousElementSibling

2  Asked on November 7, 2021 by jens-trnell

     

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir