LongSummaryStatistics.java revision b4998e53d91ce1decfa7c7634d80143626cf7fa1
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// TODO: Revert changes from {@linkplain} and {@link} to {@code} once
31// the streams changes have landed.
32/**
33 * A state object for collecting statistics such as count, min, max, sum, and
34 * average.
35 *
36 * <p>This class is designed to work with (though does not require)
37 * {@code java.util.stream streams}. For example, you can compute
38 * summary statistics on a stream of longs with:
39 * <pre> {@code
40 * LongSummaryStatistics stats = longStream.collect(LongSummaryStatistics::new,
41 *                                                  LongSummaryStatistics::accept,
42 *                                                  LongSummaryStatistics::combine);
43 * }</pre>
44 *
45 * <p>{@code LongSummaryStatistics} can be used as a
46 * {@code java.util.stream.Stream#collect(Collector)} reduction}
47 * target for a {@code java.util.stream.Stream stream}. For example:
48 *
49 * <pre> {@code
50 * LongSummaryStatistics stats = people.stream()
51 *                                     .collect(Collectors.summarizingLong(Person::getAge));
52 *}</pre>
53 *
54 * This computes, in a single pass, the count of people, as well as the minimum,
55 * maximum, sum, and average of their ages.
56 *
57 * @implNote This implementation is not thread safe. However, it is safe to use
58 * {@code java.util.stream.Collectors#summarizingLong(java.util.function.ToLongFunction)
59 * Collectors.toLongStatistics()} on a parallel stream, because the parallel
60 * implementation of {@code java.util.stream.Stream#collect Stream.collect()}
61 * provides the necessary partitioning, isolation, and merging of results for
62 * safe and efficient parallel execution.
63 *
64 * <p>This implementation does not check for overflow of the sum.
65 * @since 1.8
66 */
67public class LongSummaryStatistics implements LongConsumer, IntConsumer {
68    private long count;
69    private long sum;
70    private long min = Long.MAX_VALUE;
71    private long max = Long.MIN_VALUE;
72
73    /**
74     * Construct an empty instance with zero count, zero sum,
75     * {@code Long.MAX_VALUE} min, {@code Long.MIN_VALUE} max and zero
76     * average.
77     */
78    public LongSummaryStatistics() { }
79
80    /**
81     * Records a new {@code int} value into the summary information.
82     *
83     * @param value the input value
84     */
85    @Override
86    public void accept(int value) {
87        accept((long) value);
88    }
89
90    /**
91     * Records a new {@code long} value into the summary information.
92     *
93     * @param value the input value
94     */
95    @Override
96    public void accept(long value) {
97        ++count;
98        sum += value;
99        min = Math.min(min, value);
100        max = Math.max(max, value);
101    }
102
103    /**
104     * Combines the state of another {@code LongSummaryStatistics} into this
105     * one.
106     *
107     * @param other another {@code LongSummaryStatistics}
108     * @throws NullPointerException if {@code other} is null
109     */
110    public void combine(LongSummaryStatistics other) {
111        count += other.count;
112        sum += other.sum;
113        min = Math.min(min, other.min);
114        max = Math.max(max, other.max);
115    }
116
117    /**
118     * Returns the count of values recorded.
119     *
120     * @return the count of values
121     */
122    public final long getCount() {
123        return count;
124    }
125
126    /**
127     * Returns the sum of values recorded, or zero if no values have been
128     * recorded.
129     *
130     * @return the sum of values, or zero if none
131     */
132    public final long getSum() {
133        return sum;
134    }
135
136    /**
137     * Returns the minimum value recorded, or {@code Long.MAX_VALUE} if no
138     * values have been recorded.
139     *
140     * @return the minimum value, or {@code Long.MAX_VALUE} if none
141     */
142    public final long getMin() {
143        return min;
144    }
145
146    /**
147     * Returns the maximum value recorded, or {@code Long.MIN_VALUE} if no
148     * values have been recorded
149     *
150     * @return the maximum value, or {@code Long.MIN_VALUE} if none
151     */
152    public final long getMax() {
153        return max;
154    }
155
156    /**
157     * Returns the arithmetic mean of values recorded, or zero if no values have been
158     * recorded.
159     *
160     * @return The arithmetic mean of values, or zero if none
161     */
162    public final double getAverage() {
163        return getCount() > 0 ? (double) getSum() / getCount() : 0.0d;
164    }
165
166    @Override
167    /**
168     * {@inheritDoc}
169     *
170     * Returns a non-empty string representation of this object suitable for
171     * debugging. The exact presentation format is unspecified and may vary
172     * between implementations and versions.
173     */
174    public String toString() {
175        return String.format(
176            "%s{count=%d, sum=%d, min=%d, average=%f, max=%d}",
177            this.getClass().getSimpleName(),
178            getCount(),
179            getSum(),
180            getMin(),
181            getAverage(),
182            getMax());
183    }
184}
185