1 /*
   2  * Copyright (c) 2012, 2017, 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.IntConsumer;
  28 import java.util.function.LongConsumer;
  29 import java.util.stream.Collector;
  30 
  31 /**
  32  * A state object for collecting statistics such as count, min, max, sum, and
  33  * average.
  34  *
  35  * <p>This class is designed to work with (though does not require)
  36  * {@linkplain java.util.stream streams}. For example, you can compute
  37  * summary statistics on a stream of longs with:
  38  * <pre> {@code
  39  * LongSummaryStatistics stats = longStream.collect(LongSummaryStatistics::new,
  40  *                                                  LongSummaryStatistics::accept,
  41  *                                                  LongSummaryStatistics::combine);
  42  * }</pre>
  43  *
  44  * <p>{@code LongSummaryStatistics} can be used as a
  45  * {@linkplain java.util.stream.Stream#collect(Collector) reduction}
  46  * target for a {@linkplain java.util.stream.Stream stream}. For example:
  47  *
  48  * <pre> {@code
  49  * LongSummaryStatistics stats = people.stream()
  50  *                                     .collect(Collectors.summarizingLong(Person::getAge));
  51  *}</pre>
  52  *
  53  * This computes, in a single pass, the count of people, as well as the minimum,
  54  * maximum, sum, and average of their ages.
  55  *
  56  * @implNote This implementation is not thread safe. However, it is safe to use
  57  * {@link java.util.stream.Collectors#summarizingLong(java.util.function.ToLongFunction)
  58  * Collectors.summarizingLong()} on a parallel stream, because the parallel
  59  * implementation of {@link java.util.stream.Stream#collect Stream.collect()}
  60  * provides the necessary partitioning, isolation, and merging of results for
  61  * safe and efficient parallel execution.
  62  *
  63  * <p>This implementation does not check for overflow of the sum.
  64  * @since 1.8
  65  */
  66 public class LongSummaryStatistics implements LongConsumer, IntConsumer {
  67     private long count;
  68     private long sum;
  69     private long min = Long.MAX_VALUE;
  70     private long max = Long.MIN_VALUE;
  71 
  72     /**
  73      * Constructs an empty instance with zero count, zero sum,
  74      * {@code Long.MAX_VALUE} min, {@code Long.MIN_VALUE} max and zero
  75      * average.
  76      */
  77     public LongSummaryStatistics() { }
  78 
  79     /**
  80      * Constructs a non-empty instance with the specified {@code count},
  81      * {@code min}, {@code max}, and {@code sum}.
  82      *
  83      * <p>If {@code count} is zero then the remaining arguments are ignored and
  84      * an empty instance is constructed.
  85      *
  86      * <p>If the arguments are inconsistent then an {@code IllegalArgumentException}
  87      * is thrown.  The necessary consistent argument conditions are:
  88      * <ul>
  89      *   <li>{@code count >= 0}</li>
  90      *   <li>{@code min <= max}</li>
  91      * </ul>
  92      * @apiNote
  93      * The enforcement of argument correctness means that the retrieved set of
  94      * recorded values obtained from a {@code LongSummaryStatistics} source
  95      * instance may not be a legal set of arguments for this constructor due to
  96      * arithmetic overflow of the source's recorded count of values.
  97      * The consistent argument conditions are not sufficient to prevent the
  98      * creation of an internally inconsistent instance.  An example of such a
  99      * state would be an instance with: {@code count} = 2, {@code min} = 1,
 100      * {@code max} = 2, and {@code sum} = 0.
 101      *
 102      * @param count the count of values
 103      * @param min the minimum value
 104      * @param max the maximum value
 105      * @param sum the sum of all values
 106      * @throws IllegalArgumentException if the arguments are inconsistent
 107      * @since 10
 108      */
 109     public LongSummaryStatistics(long count, long min, long max, long sum)
 110             throws IllegalArgumentException {
 111         if (count < 0L) {
 112             throw new IllegalArgumentException("Negative count value");
 113         } else if (count > 0L) {
 114             if (min > max) throw new IllegalArgumentException("Minimum greater than maximum");
 115 
 116             this.count = count;
 117             this.sum = sum;
 118             this.min = min;
 119             this.max = max;
 120         }
 121         // Use default field values if count == 0
 122     }
 123 
 124     /**
 125      * Records a new {@code int} value into the summary information.
 126      *
 127      * @param value the input value
 128      */
 129     @Override
 130     public void accept(int value) {
 131         accept((long) value);
 132     }
 133 
 134     /**
 135      * Records a new {@code long} value into the summary information.
 136      *
 137      * @param value the input value
 138      */
 139     @Override
 140     public void accept(long value) {
 141         ++count;
 142         sum += value;
 143         min = Math.min(min, value);
 144         max = Math.max(max, value);
 145     }
 146 
 147     /**
 148      * Combines the state of another {@code LongSummaryStatistics} into this
 149      * one.
 150      *
 151      * @param other another {@code LongSummaryStatistics}
 152      * @throws NullPointerException if {@code other} is null
 153      */
 154     public void combine(LongSummaryStatistics other) {
 155         count += other.count;
 156         sum += other.sum;
 157         min = Math.min(min, other.min);
 158         max = Math.max(max, other.max);
 159     }
 160 
 161     /**
 162      * Returns the count of values recorded.
 163      *
 164      * @return the count of values
 165      */
 166     public final long getCount() {
 167         return count;
 168     }
 169 
 170     /**
 171      * Returns the sum of values recorded, or zero if no values have been
 172      * recorded.
 173      *
 174      * @return the sum of values, or zero if none
 175      */
 176     public final long getSum() {
 177         return sum;
 178     }
 179 
 180     /**
 181      * Returns the minimum value recorded, or {@code Long.MAX_VALUE} if no
 182      * values have been recorded.
 183      *
 184      * @return the minimum value, or {@code Long.MAX_VALUE} if none
 185      */
 186     public final long getMin() {
 187         return min;
 188     }
 189 
 190     /**
 191      * Returns the maximum value recorded, or {@code Long.MIN_VALUE} if no
 192      * values have been recorded
 193      *
 194      * @return the maximum value, or {@code Long.MIN_VALUE} if none
 195      */
 196     public final long getMax() {
 197         return max;
 198     }
 199 
 200     /**
 201      * Returns the arithmetic mean of values recorded, or zero if no values have been
 202      * recorded.
 203      *
 204      * @return The arithmetic mean of values, or zero if none
 205      */
 206     public final double getAverage() {
 207         return getCount() > 0 ? (double) getSum() / getCount() : 0.0d;
 208     }
 209 
 210     /**
 211      * Returns a non-empty string representation of this object suitable for
 212      * debugging. The exact presentation format is unspecified and may vary
 213      * between implementations and versions.
 214      */
 215     @Override
 216     public String toString() {
 217         return String.format(
 218             "%s{count=%d, sum=%d, min=%d, average=%f, max=%d}",
 219             this.getClass().getSimpleName(),
 220             getCount(),
 221             getSum(),
 222             getMin(),
 223             getAverage(),
 224             getMax());
 225     }
 226 }