00:00

Collectors.summarizingInt() in Java

Last updated:

Collectors.summarizingInt() is a static method of java.util.stream.Collectors, available since Java 8, that returns a Collector producing an IntSummaryStatistics object. In one pass it records the count, sum, minimum, maximum and average of the int values extracted from the elements. summarizingLong() and summarizingDouble() do the same for long and double values.

This tutorial covers the collector, the statistics object's methods, per-group statistics, empty inputs, and how it compares with IntStream.summaryStatistics().

1. Syntax and Method Signatures

Collectors.java (API)
// java.util.stream.Collectors (Java 8)
static <T> Collector<T, ?, IntSummaryStatistics>    summarizingInt(ToIntFunction<? super T> mapper)
static <T> Collector<T, ?, LongSummaryStatistics>   summarizingLong(ToLongFunction<? super T> mapper)
static <T> Collector<T, ?, DoubleSummaryStatistics> summarizingDouble(ToDoubleFunction<? super T> mapper)

// java.util.IntSummaryStatistics (Java 8)
long getCount()    long getSum()    int getMin()    int getMax()    double getAverage()

Note that IntSummaryStatistics.getSum() returns a long, so the total does not overflow even though the values are int.

2. How summarizingInt() Works

The collector creates an IntSummaryStatistics object and calls its accept(int) method for every value, which updates the count, sum, minimum and maximum. The average is computed when you ask for it, as sum divided by count. For parallel streams, partial statistics objects are merged with combine().

For an empty input, the count and sum are 0 and the average is 0.0, while getMin() returns Integer.MAX_VALUE and getMax() returns Integer.MIN_VALUE. Always check getCount() before showing min and max.

summarizingInt() computes five statistics in one pass Response times of 120, 85, 340 and 95 milliseconds are collected with summarizingInt. The result holds count 4, sum 640, min 85, max 340 and average 160.0. VALUES 120 ms 85 ms 340 ms 95 ms summarizingInt(Request::millis) STATS count 4 sum 640 min 85 max 340 avg 160.0
Figure 1: One collector replaces five separate passes over the data.

3. Java Examples

Example 1: Statistics for a list of objects (Java 16+)

Summarise API response times from a log for a performance report.

ResponseStats.java
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.stream.Collectors;

public class ResponseStats {

    record Request(String path, int millis) { }

    public static void main(String[] args) {
        List<Request> requests = List.of(
                new Request("/orders", 120), new Request("/cart", 85),
                new Request("/search", 340), new Request("/orders", 95));

        IntSummaryStatistics stats = requests.stream()
                .collect(Collectors.summarizingInt(Request::millis));

        System.out.println("Requests: " + stats.getCount());
        System.out.println("Fastest:  " + stats.getMin() + " ms");
        System.out.println("Slowest:  " + stats.getMax() + " ms");
        System.out.println("Average:  " + stats.getAverage() + " ms");
        System.out.println(stats);
    }
}
Output
Requests: 4
Fastest:  85 ms
Slowest:  340 ms
Average:  160.0 ms
IntSummaryStatistics{count=4, sum=640, min=85, average=160.000000, max=340}

How it works: One collector produces every number for the report. The object's toString() is handy for logging.

Example 2: Statistics per group (Java 16+)

Show the price range and average price of products in each category.

PriceRangePerCategory.java
import java.util.DoubleSummaryStatistics;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class PriceRangePerCategory {

    record Product(String name, String category, double price) { }

    public static void main(String[] args) {
        List<Product> products = List.of(
                new Product("Kettle", "Kitchen", 1499), new Product("Mixer", "Kitchen", 3299),
                new Product("Bulb", "Lighting", 199), new Product("Lamp", "Lighting", 899),
                new Product("Toaster", "Kitchen", 1999));

        Map<String, DoubleSummaryStatistics> stats = products.stream()
                .collect(Collectors.groupingBy(Product::category, TreeMap::new,
                        Collectors.summarizingDouble(Product::price)));

        stats.forEach((category, s) -> System.out.printf("%-9s %d items, %.0f to %.0f, average %.2f%n",
                category, s.getCount(), s.getMin(), s.getMax(), s.getAverage()));
    }
}
Output
Kitchen   3 items, 1499 to 3299, average 2265.67
Lighting  2 items, 199 to 899, average 549.00

How it works: As a downstream collector, summarizingDouble() gives every group its own statistics object. A filter panel can show price ranges from this map.

Example 3: Empty input (Java 9+)

Summarise a day with no sales and guard the display.

EmptyStats.java
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.stream.Collectors;

public class EmptyStats {

    public static void main(String[] args) {
        List<Integer> todaysSales = List.of();

        IntSummaryStatistics stats = todaysSales.stream().collect(Collectors.summarizingInt(Integer::intValue));

        System.out.println("count=" + stats.getCount() + ", sum=" + stats.getSum() + ", average=" + stats.getAverage());
        System.out.println("raw min=" + stats.getMin() + ", raw max=" + stats.getMax());
        System.out.println(stats.getCount() == 0 ? "No sales today" : "Best sale: " + stats.getMax());
    }
}
Output
count=0, sum=0, average=0.0
raw min=2147483647, raw max=-2147483648
No sales today

How it works: With no data, min and max hold sentinel values, which would be confusing on screen. Check the count first.

Example 4: Collector or primitive stream (Java 9+)

Get the same statistics from a list of exam marks in two ways.

TwoWaysToSummarise.java
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.stream.Collectors;

public class TwoWaysToSummarise {

    public static void main(String[] args) {
        List<Integer> marks = List.of(67, 82, 91, 45, 73);

        IntSummaryStatistics viaCollector = marks.stream().collect(Collectors.summarizingInt(Integer::intValue));
        IntSummaryStatistics viaIntStream = marks.stream().mapToInt(Integer::intValue).summaryStatistics();

        System.out.println(viaCollector.getAverage() + " = " + viaIntStream.getAverage());
    }
}
Output
71.6 = 71.6

How it works: mapToInt(...).summaryStatistics() is shorter for a whole stream. The collector form is needed per group or inside other collectors.

4. Real-World Use Cases

  • Performance monitoring: latency min, max and average per endpoint.
  • Catalogue filters: price range per category.
  • Education: highest, lowest and average marks per class.
  • Operations: order counts and totals per warehouse in one pass.

5. Important Points

  • One pass for count, sum, min, max and average.
  • Empty input: min and max return sentinel values; check getCount().
  • getSum() is long for IntSummaryStatistics, but each value must fit in an int.
  • Not thread-safe objects, but the collector handles parallel streams by combining partial results.
  • No median or percentiles: those need sorting or a dedicated library.

6. summarizingInt() vs Related Approaches

ApproachResultUse when
summarizingInt(f)IntSummaryStatisticsStatistics per group, or inside other collectors
mapToInt(f).summaryStatistics()IntSummaryStatisticsStatistics for a whole stream
summingInt() + averagingInt()Two valuesOnly those two are needed; but two passes
teeing() (Java 12)Any combinationTwo different collectors in one pass

7. Common Mistakes and Best Practices

Showing min and max for empty data

As Example 3 shows, an empty input reports a minimum of 2147483647. Check the count before displaying.

Computing statistics in several passes

Slower
long count = list.stream().count();
int max = list.stream().mapToInt(Item::qty).max().orElse(0);
double avg = list.stream().mapToInt(Item::qty).average().orElse(0);   // three passes
Better
IntSummaryStatistics s = list.stream().collect(Collectors.summarizingInt(Item::qty));   // one pass

Other mistakes to avoid

  • Using summarizingInt() for money with decimals. Use summarizingLong() on paise, or summarizingDouble() knowing it is approximate.
  • Expecting a median. It is not included.
  • Casting getSum() to int. It may not fit.

8. Summary

  • summarizingInt() returns count, sum, min, max and average in one pass.
  • It is ideal as a downstream collector for statistics per group.
  • On empty input, min and max hold sentinel values; check the count.
  • For a whole stream, mapToInt(...).summaryStatistics() is shorter.

9. References