IntSummaryStatistics is a Java utility class that computes five statistics about a set of integers in a single pass: count, sum, min, max, and average. It's part of java.util and works naturally with Java 8 streams.
Instead of writing separate reductions for each statistic, summaryStatistics() gives you all five at once.
Getting IntSummaryStatistics from a Stream
import java.util.IntSummaryStatistics;
import java.util.stream.Stream;
public class IntSummaryStatisticsExample {
public static void main(String[] args) {
Stream<Integer> numStream = Stream.of(1, 2, 3, 4, 5);
IntSummaryStatistics stats = numStream
.mapToInt(Integer::intValue)
.summaryStatistics();
System.out.println("Count: " + stats.getCount()); // 5
System.out.println("Sum: " + stats.getSum()); // 15
System.out.println("Min: " + stats.getMin()); // 1
System.out.println("Max: " + stats.getMax()); // 5
System.out.println("Average: " + stats.getAverage()); // 3.0
}
}
Output:
Count: 5
Sum: 15
Min: 1
Max: 5
Average: 3.0
Adding More Values with accept()
IntSummaryStatistics is mutable — you can continue feeding it new values after the initial stream:
IntSummaryStatistics stats = Stream.of(1, 2, 3, 4, 5)
.mapToInt(Integer::intValue)
.summaryStatistics();
// Add a new value after the stream is consumed
stats.accept(10);
System.out.println("Count: " + stats.getCount()); // 6
System.out.println("Sum: " + stats.getSum()); // 25
System.out.println("Min: " + stats.getMin()); // 1
System.out.println("Max: " + stats.getMax()); // 10
System.out.println("Average: " + stats.getAverage()); // 4.166...
Using with an IntStream Directly
When you already have an IntStream (e.g., from an int[] array), you don't need mapToInt():
import java.util.Arrays;
int[] values = {10, 20, 30, 40, 50};
IntSummaryStatistics stats = Arrays.stream(values).summaryStatistics();
System.out.println(stats);
// IntSummaryStatistics{count=5, sum=150, min=10, average=30.000000, max=50}
Using collect() for Custom Aggregation
You can also use Collectors.summarizingInt() when collecting from an object stream:
import java.util.List;
import java.util.stream.Collectors;
List<String> words = List.of("apple", "fig", "banana", "kiwi");
IntSummaryStatistics lengthStats = words.stream()
.collect(Collectors.summarizingInt(String::length));
System.out.println("Shortest word length: " + lengthStats.getMin()); // 3
System.out.println("Longest word length: " + lengthStats.getMax()); // 6
System.out.println("Average word length: " + lengthStats.getAverage()); // 4.75
Available Methods
| Method | Return Type | Description |
|---|---|---|
getCount() | long | Number of values |
getSum() | long | Sum of all values |
getMin() | int | Minimum value |
getMax() | int | Maximum value |
getAverage() | double | Arithmetic mean |
accept(int) | void | Add a single value |
combine(other) | void | Merge another statistics object |
Merging Two Statistics Objects with combine()
combine() merges a second IntSummaryStatistics into the current one, updating all five fields atomically:
IntSummaryStatistics batch1 = Stream.of(1, 2, 3)
.mapToInt(Integer::intValue).summaryStatistics();
IntSummaryStatistics batch2 = Stream.of(4, 5, 6)
.mapToInt(Integer::intValue).summaryStatistics();
batch1.combine(batch2);
System.out.println("Count: " + batch1.getCount()); // 6
System.out.println("Sum: " + batch1.getSum()); // 21
System.out.println("Min: " + batch1.getMin()); // 1
System.out.println("Max: " + batch1.getMax()); // 6
System.out.println("Average: " + batch1.getAverage()); // 3.5
This is useful when you're processing data in batches — compute statistics per batch, then merge them all at the end.
Using with Parallel Streams
summaryStatistics() is safe to use with parallel streams. The stream framework handles merging partial results from each thread using the combine() method internally:
IntSummaryStatistics parallelStats = IntStream.range(1, 1_000_001)
.parallel()
.summaryStatistics();
System.out.println("Sum: " + parallelStats.getSum()); // 500000500000
System.out.println("Max: " + parallelStats.getMax()); // 1000000
You get the same result as a sequential stream — parallelism is handled transparently.
LongSummaryStatistics and DoubleSummaryStatistics
Java provides equivalent classes for the other primitive numeric types:
| Class | Stream type | getSum() returns |
|---|---|---|
IntSummaryStatistics | IntStream | long |
LongSummaryStatistics | LongStream | long |
DoubleSummaryStatistics | DoubleStream | double |
// LongSummaryStatistics — for large numbers that overflow int
LongSummaryStatistics longStats = LongStream.of(1_000_000L, 2_000_000L, 3_000_000L)
.summaryStatistics();
System.out.println("Sum: " + longStats.getSum()); // 6000000
// DoubleSummaryStatistics — for floating-point values
DoubleSummaryStatistics priceStats = DoubleStream.of(9.99, 24.50, 4.99)
.summaryStatistics();
System.out.println("Avg price: $" + priceStats.getAverage()); // $13.16
Note that IntSummaryStatistics.getSum() returns long even though the inputs are int — this prevents overflow when summing many large integers.
Real-World Example: Analyzing Order Totals
import java.util.*;
import java.util.stream.*;
List<Integer> orderTotals = Arrays.asList(
120, 45, 380, 95, 210, 67, 430, 28, 150, 300
);
IntSummaryStatistics stats = orderTotals.stream()
.mapToInt(Integer::intValue)
.summaryStatistics();
System.out.println("Orders: " + stats.getCount());
System.out.println("Revenue: $" + stats.getSum());
System.out.println("Lowest: $" + stats.getMin());
System.out.println("Highest: $" + stats.getMax());
System.out.printf("Average: $%.2f%n", stats.getAverage());
// Orders: 10
// Revenue: $1825
// Lowest: $28
// Highest: $430
// Average: $182.50
Summary
IntSummaryStatistics is a clean, one-pass solution for computing common numeric statistics. Use it whenever you need more than one statistic from the same dataset — it's faster and cleaner than running separate stream operations. For large integers, use LongSummaryStatistics; for decimals, use DoubleSummaryStatistics.
No comments :
Post a Comment
Please leave your message queries or suggetions.
Note: Only a member of this blog may post a comment.