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