CKTIS / Java
Double summary statistics with Collectors.summarizingDouble
Get the count, sum, minimum, maximum, and average in one pass over an object stream by specifying how to obtain a double from each element.
Version: Java SE 21
Syntax
public static <T> Collector<T, ?, DoubleSummaryStatistics> summarizingDouble(ToDoubleFunction<? super T> mapper)Collectors.summarizingDouble() is shorthand for the static method in java.util.stream.Collectors. It has no zero-argument overload: it requires a ToDoubleFunction<? super T> that produces one primitive double from each stream element. You can supply that function as a lambda or a method reference.
Calling the method creates a collector. Pass it to the terminal operation Stream.collect(...) to get a java.util.DoubleSummaryStatistics in one pass. getCount() returns the number of values as a long; getSum(), getMin(), getMax(), and getAverage() return the sum, minimum, maximum, and arithmetic mean as double values. If you already have a DoubleStream, call its summaryStatistics() method without a mapper.
For an empty stream, the count is 0, the sum and average are 0.0, the minimum is Double.POSITIVE_INFINITY, and the maximum is Double.NEGATIVE_INFINITY. Check getCount() == 0 before treating the minimum and maximum as actual values from the data.
Floating-point rounding means the sum and average can depend on the order of addition. If any mapped value is NaN, the sum, minimum, maximum, and average are all NaN; that value still contributes to the count.
Examples
import java.util.DoubleSummaryStatistics;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
record Parcel(double weightKg) {}
public static void main(String[] args) {
List<Parcel> parcels = List.of(
new Parcel(1.5), new Parcel(2.5), new Parcel(3.5));
DoubleSummaryStatistics stats = parcels.stream()
.collect(Collectors.summarizingDouble(Parcel::weightKg));
System.out.println("count=" + stats.getCount());
System.out.println("sum=" + stats.getSum());
System.out.println("min=" + stats.getMin());
System.out.println("max=" + stats.getMax());
System.out.println("average=" + stats.getAverage());
}
}Result
count=3 sum=7.5 min=1.5 max=3.5 average=2.5
`Parcel::weightKg` extracts each parcel's weight in kilograms. The collector counts the three values and computes their statistics; the example prints each result separately.
Related lessons
- Java · Lesson 67 · Basic · Version: 2