Codectionary / Developer documentation / Java

Numeric Summary Statistics

Compute a count, sum, minimum, maximum and average in one numeric stream traversal.

What it is and why to use it

A simple report may need several measurements over the same scores. IntStream.summaryStatistics collects them together rather than consuming separate streams for each value. Its IntSummaryStatistics result exposes named accessors, which make the report easier to understand.

How it works

mapToInt converts boxed Integer elements into an IntStream. summaryStatistics is a terminal operation that consumes that stream and records count, sum, min, max and average. The example prints individual fields so output does not depend on the statistics object’s formatted toString representation.

Common mistakes and limitations

Check count before treating an empty stream’s min or max as a real measurement: their empty-state values are integer sentinels. Average is 0.0 for empty input, which alone does not prove an actual zero score. Long sums can still overflow for sufficiently large totals.

Try it and keep learning

Save the complete example below as Main.java. With a JDK supporting Java 17, compile using javac --release 17 Main.java, then run java Main from the same directory. These examples need only the standard library and fixed input; they do not require packages, files or network access.

Syntax

IntSummaryStatistics stats = values.stream().mapToInt(Integer::intValue).summaryStatistics();

Examples

Numeric Summary Statistics

Complete Main.java example — Java 17 or later, without preview features.

import java.util.IntSummaryStatistics;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    IntSummaryStatistics stats = List.of(60, 80, 100).stream()
        .mapToInt(Integer::intValue).summaryStatistics();
    System.out.println(stats.getCount());
    System.out.println(stats.getSum());
    System.out.println(stats.getMin() + " / " + stats.getMax());
    System.out.println(stats.getAverage());
  }
}
  1. Three scores enter the primitive stream, and summaryStatistics processes all three.
  2. Count is 3 and sum is 240; the smallest and largest values are 60 and 100.
  3. The average is 240 divided by 3, printed as double 80.0. This is useful for a summary panel that needs several measurements at once.
  4. Expected output: 3 240 60 / 100 80.0

Best practices

  • Handle empty input explicitly.
  • Choose long or decimal arithmetic where the domain requires it.

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading