java 32 lines · 5 steps

Aggregating stats with IntSummaryStatistics

How a single stream pass collects count, min, max, sum, and average from a list of orders.

Explained by highlit
1import java.util.List;
2import java.util.IntSummaryStatistics;
3 
4public class OrderReport {
5 
6 public record Order(String customer, int itemCount, double total) {}
7 
8 public String summarizeItemCounts(List<Order> orders) {
9 IntSummaryStatistics stats = orders.stream()
10 .mapToInt(Order::itemCount)
11 .summaryStatistics();
12 
13 if (stats.getCount() == 0) {
14 return "No orders to report.";
15 }
16 
17 return String.format(
18 "Orders: %d | items min=%d, max=%d, sum=%d, avg=%.2f",
19 stats.getCount(),
20 stats.getMin(),
21 stats.getMax(),
22 stats.getSum(),
23 stats.getAverage());
24 }
25 
26 public boolean hasBulkOrder(List<Order> orders, int threshold) {
27 return orders.stream()
28 .mapToInt(Order::itemCount)
29 .summaryStatistics()
30 .getMax() >= threshold;
31 }
32}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1IntSummaryStatistics gathers count, min, max, sum, and average in one stream traversal.
  2. 2Guarding against an empty stream avoids meaningless zero or infinity results before formatting.
  3. 3Method references like Order::itemCount turn a record accessor into a clean projection for mapToInt.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Aggregating stats with IntSummaryStatistics — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code