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. The sum returned can vary depending upon the order in which
 115      * values are recorded. This is due to accumulated rounding error in
 116      * addition of values of differing magnitudes. Values sorted by increasing
 117      * absolute magnitude tend to yield more accurate results.  If any recorded
 118      * value is a {@code NaN} or the sum is at any point a {@code NaN} then the
 119      * sum will be {@code NaN}.
 120      *
 121      * @return the sum of values, or zero if none
 122      */
 123     public final double getSum() {
 124         return sum;
 125     }
 126 
 127     /**
 128      * Returns the minimum recorded value, {@code Double.NaN} if any recorded
 129      * value was NaN or {@code Double.POSITIVE_INFINITY} if no values were
 130      * recorded. Unlike the numerical comparison operators, this method
 131      * considers negative zero to be strictly smaller than positive zero.
 132      *
 133      * @return the minimum recorded value, {@code Double.NaN} if any recorded
 134      * value was NaN or {@code Double.POSITIVE_INFINITY} if no values were
 135      * recorded
 136      */
 137     public final double getMin() {
 138         return min;
 139     }
 140 
 141     /**
 142      * Returns the maximum recorded value, {@code Double.NaN} if any recorded
 143      * value was NaN or {@code Double.NEGATIVE_INFINITY} if no values were
 144      * recorded. Unlike the numerical comparison operators, this method
 145      * considers negative zero to be strictly smaller than positive zero.
 146      *
 147      * @return the maximum recorded value, {@code Double.NaN} if any recorded
 148      * value was NaN or {@code Double.NEGATIVE_INFINITY} if no values were
 149      * recorded
 150      */
 151     public final double getMax() {
 152         return max;
 153     }
 154 
 155     /**
 156      * Returns the arithmetic mean of values recorded, or zero if no values have been
 157      * recorded. The average returned can vary depending upon the order in
 158      * which values are recorded. This is due to accumulated rounding error in
 159      * addition of values of differing magnitudes. Values sorted by increasing
 160      * absolute magnitude tend to yield more accurate results. If any recorded
 161      * value is a {@code NaN} or the sum is at any point a {@code NaN} then the
 162      * average will be {@code NaN}.
 163      *
 164      * @return the arithmetic mean of values, or zero if none
 165      */
 166     public final double getAverage() {
 167         return getCount() > 0 ? getSum() / getCount() : 0.0d;
 168     }
 169 
 170     /**
 171      * {@inheritDoc}
 172      *
 173      * Returns a non-empty string representation of this object suitable for
 174      * debugging. The exact presentation format is unspecified and may vary
 175      * between implementations and versions.
 176      */
 177     @Override
 178     public String toString() {
 179         return String.format(
 180             "%s{count=%d, sum=%f, min=%f, average=%f, max=%f}",
 181             this.getClass().getSimpleName(),
 182             getCount(),
 183             getSum(),
 184             getMin(),
 185             getAverage(),
 186             getMax());
 187     }
 188 }