In Stream reduce method, must the identity always be 0 for sum and 1 for multiplication?

前端 未结 7 876
执念已碎
执念已碎 2020-11-29 06:05

I proceed with java 8 learning.

I have found an interesting behavior:

let\'s see code sample:

// identity value and accumulator and combiner         


        
7条回答
  •  猫巷女王i
    2020-11-29 06:31

    The JavaDoc documentation for Stream.reduce specifically states that

    The identity value must be an identity for the combiner function

    1 is not an identity value for the addition operator, which is why you get unexpected results. If you used 0 (which is the addition operator's identity value) then you'd get the same result from serial and parallel streams.

提交回复
热议问题