LongSummaryStatistics.java revision 91bae3c5d9142b9cb2877736523bbf0c9385b209
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 */
25package java.util;
26
27import java.util.function.IntConsumer;
28import java.util.function.LongConsumer;
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 longs with:
37 * <pre> {@code
38 * LongSummaryStatistics stats = longStream.collect(LongSummaryStatistics::new,
39 *                                                  LongSummaryStatistics::accept,
40 *                                                  LongSummaryStatistics::combine);
41 * }</pre>
42 *
43 * <p>{@code LongSummaryStatistics} 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 * LongSummaryStatistics stats = people.stream()
49 *                                     .collect(Collectors.summarizingLong(Person::getAge));
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 ages.
54 *
55 * @implNote This implementation is not thread safe. However, it is safe to use
56 * {@link java.util.stream.Collectors#summarizingLong(java.util.function.ToLongFunction)
57 * Collectors.toLongStatistics()} 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 sum.
63 * @since 1.8
64 */
65public class LongSummaryStatistics implements LongConsumer, IntConsumer {
66    private long count;
67    private long sum;
68    private long min = Long.MAX_VALUE;
69    private long max = Long.MIN_VALUE;
70
71    /**
72     * Construct an empty instance with zero count, zero sum,
73     * {@code Long.MAX_VALUE} min, {@code Long.MIN_VALUE} max and zero
74     * average.
75     */
76    public LongSummaryStatistics() { }
77
78    /**
79     * Records a new {@code int} value into the summary information.
80     *
81     * @param value the input value
82     */
83    @Override
84    public void accept(int value) {
85        accept((long) value);
86    }
87
88    /**
89     * Records a new {@code long} value into the summary information.
90     *
91     * @param value the input value
92     */
93    @Override
94    public void accept(long value) {
95        ++count;
96        sum += value;
97        min = Math.min(min, value);
98        max = Math.max(max, value);
99    }
100
101    /**
102     * Combines the state of another {@code LongSummaryStatistics} into this
103     * one.
104     *
105     * @param other another {@code LongSummaryStatistics}
106     * @throws NullPointerException if {@code other} is null
107     */
108    public void combine(LongSummaryStatistics other) {
109        count += other.count;
110        sum += other.sum;
111        min = Math.min(min, other.min);
112        max = Math.max(max, other.max);
113    }
114
115    /**
116     * Returns the count of values recorded.
117     *
118     * @return the count of values
119     */
120    public final long getCount() {
121        return count;
122    }
123
124    /**
125     * Returns the sum of values recorded, or zero if no values have been
126     * recorded.
127     *
128     * @return the sum of values, or zero if none
129     */
130    public final long getSum() {
131        return sum;
132    }
133
134    /**
135     * Returns the minimum value recorded, or {@code Long.MAX_VALUE} if no
136     * values have been recorded.
137     *
138     * @return the minimum value, or {@code Long.MAX_VALUE} if none
139     */
140    public final long getMin() {
141        return min;
142    }
143
144    /**
145     * Returns the maximum value recorded, or {@code Long.MIN_VALUE} if no
146     * values have been recorded
147     *
148     * @return the maximum value, or {@code Long.MIN_VALUE} if none
149     */
150    public final long getMax() {
151        return max;
152    }
153
154    /**
155     * Returns the arithmetic mean of values recorded, or zero if no values have been
156     * recorded.
157     *
158     * @return The arithmetic mean of values, or zero if none
159     */
160    public final double getAverage() {
161        return getCount() > 0 ? (double) getSum() / getCount() : 0.0d;
162    }
163
164    @Override
165    /**
166     * {@inheritDoc}
167     *
168     * Returns a non-empty string representation of this object suitable for
169     * debugging. The exact presentation format is unspecified and may vary
170     * between implementations and versions.
171     */
172    public String toString() {
173        return String.format(
174            "%s{count=%d, sum=%d, min=%d, average=%f, max=%d}",
175            this.getClass().getSimpleName(),
176            getCount(),
177            getSum(),
178            getMin(),
179            getAverage(),
180            getMax());
181    }
182}
183