Difference in Stream.reduce with identity and Stream.reduce().orElse() is case of bit wise OR reduction

707 views Asked by At

I tried the below two set of codes and couldn't see any difference in the results. I also tried to go through the implementation of both reduce(T identity, BinaryOperator<T> accumulator) and reduce(BinaryOperator<T> accumulator) and was not able to note any difference when the accumulator function is bitwise OR.

long result1 = myList.stream.reduce((a,b) -> a|b).orElse(0L);
long result2 = myList.stream.reduce(0L,(a,b) -> a|b);

Are there any corner cases which would cause a different result or is one better than the other in any way?

1

There are 1 answers

4
Andreas On BEST ANSWER

There is no difference in the results.

I would however unbox the Stream<Long> elements into a LongStream, so the accumulator won't need to autobox the result(s).

With that, I'd use the second option.

long result = myList.stream()
        .mapToLong(Long::longValue)
        .reduce(0L, (a, b) -> a | b);