1 /*
   2  * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 package java.util;
  26 
  27 import java.util.function.DoubleConsumer;
  28 import java.util.stream.Collector;
  29 
  30 /**
  31  * A state object for collecting statistics such as count, min, max, sum, and
  32  * average.
  33  *
  34  * <p>This class is designed to work with (though does not require)
  35  * {@linkplain java.util.stream streams}. For example, you can compute
  36  * summary statistics on a stream of doubles with:
  37  * <pre> {@code
  38  * DoubleSummaryStatistics stats = doubleStream.collect(DoubleSummaryStatistics::new,
  39  *                                                      DoubleSummaryStatistics::accept,
  40  *                                                      DoubleSummaryStatistics::combine);
  41  * }</pre>
  42  *
  43  * <p>{@code DoubleSummaryStatistics} can be used as a
  44  * {@linkplain java.util.stream.Stream#collect(Collector) reduction}
  45  * target for a {@linkplain java.util.stream.Stream stream}. For example:
  46  *
  47  * <pre> {@code
  48  * DoubleSummaryStatistics stats = people.stream()
  49  *     .collect(Collectors.summarizingDouble(Person::getWeight));
  50  *}</pre>
  51  *
  52  * This computes, in a single pass, the count of people, as well as the minimum,
  53  * maximum, sum, and average of their weights.
  54  *
  55  * @implNote This implementation is not thread safe. However, it is safe to use
  56  * {@link java.util.stream.Collectors#summarizingDouble(java.util.function.ToDoubleFunction)
  57  * Collectors.toDoubleStatistics()} on a parallel stream, because the parallel
  58  * implementation of {@link java.util.stream.Stream#collect Stream.collect()}
  59  * provides the necessary partitioning, isolation, and merging of results for
  60  * safe and efficient parallel execution.
  61  * @since 1.8
  62  */
  63 public class DoubleSummaryStatistics implements DoubleConsumer {
  64     private long count;
  65     private double sum;
  66     private double min = Double.POSITIVE_INFINITY;
  67     private double max = Double.NEGATIVE_INFINITY;
  68 
  69     /**
  70      * Construct an empty instance with zero count, zero sum,
  71      * {@code Double.POSITIVE_INFINITY} min, {@code Double.NEGATIVE_INFINITY}
  72      * max and zero average.
  73      */
  74     public DoubleSummaryStatistics() { }
  75 
  76     /**
  77      * Records another value into the summary information.
  78      *
  79      * @param value the input value
  80      */
  81     @Override
  82     public void accept(double value) {
  83         ++count;
  84         sum += value;
  85         min = Math.min(min, value);
  86         max = Math.max(max, value);
  87     }
  88 
  89     /**
  90      * Combines the state of another {@code DoubleSummaryStatistics} into this
  91      * one.
  92      *
  93      * @param other another {@code DoubleSummaryStatistics}
  94      * @throws NullPointerException if {@code other} is null
  95      */
  96     public void combine(DoubleSummaryStatistics other) {
  97         count += other.count;
  98         sum += other.sum;
  99         min = Math.min(min, other.min);
 100         max = Math.max(max, other.max);
 101     }
 102 
 103     /**
 104      * Return the count of values recorded.
 105      *
 106      * @return the count of values
 107      */
 108     public final long getCount() {
 109         return count;
 110     }
 111 
 112     /**
 113      * Returns the sum of values recorded, or zero if no values have been
 114      * recorded.
 115      *
 116      * If any recorded value is a NaN or the sum is at any point a NaN
 117      * then the sum will be NaN.
 118      *
 119      * <p> The value of a floating-point sum is a function both of the
 120      * input values as well as the order of addition operations. The
 121      * order of addition operations of this method is intentionally
 122      * not defined to allow for implementation flexibility to improve
 123      * the speed and accuracy of the computed result.
 124      *
 125      * In particular, this method may be implemented using compensated
 126      * summation or other technique to reduce the error bound in the
 127      * numerical sum compared to a simple summation of {@code double}
 128      * values.
 129      *
 130      * @apiNote Values sorted by increasing absolute magnitude tend to yield
 131      * more accurate results.
 132      *
 133      * @return the sum of values, or zero if none
 134      */
 135     public final double getSum() {
 136         return sum;
 137     }
 138 
 139     /**
 140      * Returns the minimum recorded value, {@code Double.NaN} if any recorded
 141      * value was NaN or {@code Double.POSITIVE_INFINITY} if no values were
 142      * recorded. Unlike the numerical comparison operators, this method
 143      * considers negative zero to be strictly smaller than positive zero.
 144      *
 145      * @return the minimum recorded value, {@code Double.NaN} if any recorded
 146      * value was NaN or {@code Double.POSITIVE_INFINITY} if no values were
 147      * recorded
 148      */
 149     public final double getMin() {
 150         return min;
 151     }
 152 
 153     /**
 154      * Returns the maximum recorded value, {@code Double.NaN} if any recorded
 155      * value was NaN or {@code Double.NEGATIVE_INFINITY} if no values were
 156      * recorded. Unlike the numerical comparison operators, this method
 157      * considers negative zero to be strictly smaller than positive zero.
 158      *
 159      * @return the maximum recorded value, {@code Double.NaN} if any recorded
 160      * value was NaN or {@code Double.NEGATIVE_INFINITY} if no values were
 161      * recorded
 162      */
 163     public final double getMax() {
 164         return max;
 165     }
 166 
 167     /**
 168      * Returns the arithmetic mean of values recorded, or zero if no
 169      * values have been recorded.
 170      *
 171      * If any recorded value is a NaN or the sum is at any point a NaN
 172      * then the average will be code NaN.
 173      *
 174      * <p>The average returned can vary depending upon the order in
 175      * which values are recorded.
 176      *
 177      * This method may be implemented using compensated summation or
 178      * other technique to reduce the error bound in the {@link #getSum
 179      * numerical sum} used to compute the average.
 180      *
 181      * @apiNote Values sorted by increasing absolute magnitude tend to yield
 182      * more accurate results.
 183      *
 184      * @return the arithmetic mean of values, or zero if none
 185      */
 186     public final double getAverage() {
 187         return getCount() > 0 ? getSum() / getCount() : 0.0d;
 188     }
 189 
 190     /**
 191      * {@inheritDoc}
 192      *
 193      * Returns a non-empty string representation of this object suitable for
 194      * debugging. The exact presentation format is unspecified and may vary
 195      * between implementations and versions.
 196      */
 197     @Override
 198     public String toString() {
 199         return String.format(
 200             "%s{count=%d, sum=%f, min=%f, average=%f, max=%f}",
 201             this.getClass().getSimpleName(),
 202             getCount(),
 203             getSum(),
 204             getMin(),
 205             getAverage(),
 206             getMax());
 207     }
 208 }