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 
  29 /**
  30  * A state object for collecting statistics such as count, min, max, sum, and
  31  * average.
  32  *
  33  * <p>This class is designed to work with (though does not require)
  34  * {@linkplain java.util.stream streams}. For example, you can compute
  35  * summary statistics on a stream of doubles with:
  36  * <pre> {@code
  37  * DoubleSummaryStatistics stats = doubleStream.collect(DoubleSummaryStatistics::new,
  38  *     DoubleSummaryStatistics::accept,
  39  *     DoubleSummaryStatistics::combine);
  40  * }</pre>
  41  *
  42  * <p>{@code DoubleSummaryStatistics} can be used as a
  43  * {@linkplain java.util.stream.Stream#reduce(java.util.function.BinaryOperator) reduction}
  44  * target for a {@linkplain java.util.stream.Stream stream}. For example:
  45  *
  46  * <pre> {@code
  47  * DoubleSummaryStatistics stats = people.stream()
  48  *     .collect(Collectors.toDoubleSummaryStatistics(Person::getWeight));
  49  *}</pre>
  50  *
  51  * This computes, in a single pass, the count of people, as well as the minimum,
  52  * maximum, sum, and average of their weights.
  53  *
  54  * @implNote This implementation is not thread safe. However, it is safe to use
  55  * {@link java.util.stream.Collectors#toDoubleSummaryStatistics(java.util.function.ToDoubleFunction)
  56  * Collectors.toDoubleStatistics()} on a parallel stream, because the parallel
  57  * implementation of {@link java.util.stream.Stream#collect Stream.collect()}
  58  * provides the necessary partitioning, isolation, and merging of results for
  59  * safe and efficient parallel execution.
  60  * @since 1.8
  61  */
  62 public class DoubleSummaryStatistics implements DoubleConsumer {
  63     private long count;
  64     private double sum;
  65     private double min = Double.POSITIVE_INFINITY;
  66     private double max = Double.NEGATIVE_INFINITY;
  67 
  68     /**
  69      * Construct an empty instance with zero count, zero sum,
  70      * {@code Double.POSITIVE_INFINITY} min, {@code Double.NEGATIVE_INFINITY}
  71      * max and zero average.
  72      */
  73     public DoubleSummaryStatistics() { }
  74 
  75     /**
  76      * Records another value into the summary information.
  77      *
  78      * @param value the input value
  79      */
  80     @Override
  81     public void accept(double value) {
  82         ++count;
  83         sum += value;
  84         min = Math.min(min, value);
  85         max = Math.max(max, value);
  86     }
  87 
  88     /**
  89      * Combines the state of another {@code DoubleSummaryStatistics} into this
  90      * one.
  91      *
  92      * @param other another {@code DoubleSummaryStatistics}
  93      * @throws NullPointerException if {@code other} is null
  94      */
  95     public void combine(DoubleSummaryStatistics other) {
  96         count += other.count;
  97         sum += other.sum;
  98         min = Math.min(min, other.min);
  99         max = Math.max(max, other.max);
 100     }
 101 
 102     /**
 103      * Return the count of values recorded.
 104      *
 105      * @return the count of values
 106      */
 107     public final long getCount() {
 108         return count;
 109     }
 110 
 111     /**
 112      * Returns the sum of values recorded, or zero if no values have been
 113      * recorded. The sum returned can vary depending upon the order in which
 114      * values are recorded. This is due to accumulated rounding error in
 115      * addition of values of differing magnitudes. Values sorted by increasing
 116      * absolute magnitude tend to yield more accurate results.  If any recorded
 117      * value is a {@code NaN} or the sum is at any point a {@code NaN} then the
 118      * sum will be {@code NaN}.
 119      *
 120      * @return the sum of values, or zero if none
 121      */
 122     public final double getSum() {
 123         return sum;
 124     }
 125 
 126     /**
 127      * Returns the minimum recorded value, {@code Double.NaN} if any recorded
 128      * value was NaN or {@code Double.POSITIVE_INFINITY} if no values were
 129      * recorded. Unlike the numerical comparison operators, this method
 130      * considers negative zero to be strictly smaller than positive zero.
 131      *
 132      * @return the minimum recorded value, {@code Double.NaN} if any recorded
 133      * value was NaN or {@code Double.POSITIVE_INFINITY} if no values were
 134      * recorded
 135      */
 136     public final double getMin() {
 137         return min;
 138     }
 139 
 140     /**
 141      * Returns the maximum recorded value, {@code Double.NaN} if any recorded
 142      * value was NaN or {@code Double.NEGATIVE_INFINITY} if no values were
 143      * recorded. Unlike the numerical comparison operators, this method
 144      * considers negative zero to be strictly smaller than positive zero.
 145      *
 146      * @return the maximum recorded value, {@code Double.NaN} if any recorded
 147      * value was NaN or {@code Double.NEGATIVE_INFINITY} if no values were
 148      * recorded
 149      */
 150     public final double getMax() {
 151         return max;
 152     }
 153 
 154     /**
 155      * Returns the average of values recorded, or zero if no values have been
 156      * recorded. The average returned can vary depending upon the order in
 157      * which values are recorded. This is due to accumulated rounding error in
 158      * addition of values of differing magnitudes. Values sorted by increasing
 159      * absolute magnitude tend to yield more accurate results. If any recorded
 160      * value is a {@code NaN} or the sum is at any point a {@code NaN} then the
 161      * average will be {@code NaN}.
 162      *
 163      * @return the average of values, or zero if none
 164      */
 165     public final double getAverage() {
 166         return getCount() > 0 ? getSum() / getCount() : 0.0d;
 167     }
 168 
 169     /**
 170      * {@inheritDoc}
 171      *
 172      * Returns a non-empty string representation of this object suitable for
 173      * debugging. The exact presentation format is unspecified and may vary
 174      * between implementations and versions.
 175      */
 176     @Override
 177     public String toString() {
 178         return String.format(
 179             "%s{count=%d, sum=%f, min=%f, average=%f, max=%f}",
 180             this.getClass().getSimpleName(),
 181             getCount(),
 182             getSum(),
 183             getMin(),
 184             getAverage(),
 185             getMax());
 186     }
 187 }