Possible long overflow in Collectors.averagingLong and LongStream.average

Tagir F. Valeev amaembo at gmail.com
Wed Aug 12 08:47:16 UTC 2015


The following code prints -1 twice, while users would normally expect
something like 9.223372036854776E18:

double avg1 = Stream.of(Long.MAX_VALUE, Long.MAX_VALUE).collect(

double avg2 = LongStream.of(Long.MAX_VALUE, Long.MAX_VALUE).average()

That's because in both cases internally sum is calculated in the long
variable where it may silently overflow. The documentation for both
methods says nothing about such possibility. I guess if it's too late
to fix this behavior, then probably it should be at least properly

With best regards,
Tagir Valeev.

More information about the core-libs-dev mailing list