Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8073940

IntStream/LongStream/DoubleStream: sum() specifications must be expanded

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Unresolved
    • Icon: P4 P4
    • tbd
    • 8, 9
    • core-libs

      FULL PRODUCT VERSION :
      java version "1.8.0_31"
      Java(TM) SE Runtime Environment (build 1.8.0_31-b13)
      Java HotSpot(TM) 64-Bit Server VM (build 25.31-b07, mixed mode)

      ADDITIONAL OS VERSION INFORMATION :
      Microsoft Windows [Version 6.3.9600]

      A DESCRIPTION OF THE PROBLEM :
      In the package java.util.stream, the classes DoubleStream, LongStream, IntStream all provide a "sum()" method. However, it may be impossible to retrieve the exact sum with these methods:
      IntStream and LongStream are subject to overflow & may thus even return a negative result
      DoubleStream provides a reasonable result, but is inherently not precise when the result gets too big

      In my opinion, the javadoc of the sum-related methods should be updated:
      for IntStream:
      * refer to the method "summaryStatistics()", since the getSum() of IntSummaryStatistics returns long (instead of "int" from the sum() of IntStream, so overflow is already much more unlikely)

      for IntStream/LongStream:
      * warn about overflow

      for IntStream/LongStream/DoubleStream:
      * an example of how to do an exact summing reduction
      for IntStream/LongStream: stream.boxed().map(BigInteger::valueOf).reduce(BigInteger.ZERO, BigInteger::add);
      for DoubleStream: stream.boxed().map(BigDecimal::valueOf).reduce(BigDecimal.ZERO, BigDecimal::add);

      * a warning about the trade-off between robustness & performance: there's no use in doing an exact reduction if you know for a fact that overflow cannot occur



      REPRODUCIBILITY :
      This bug can be reproduced always.

            psandoz Paul Sandoz
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated: