LongSummaryStatistics Grouped Rollup

Roll up grouped long metrics with Collectors.summarizingLong and LongSummaryStatistics, keeping count, sum, min, and max together per group.

JavaData Fetching

Code

snippet
import java.util.List;
import java.util.Map;
import java.util.LongSummaryStatistics;
import java.util.stream.Collectors;

public class TrafficRollup {

    record Hit(String route, long bytes) {}

    public static void main(String[] args) {
        List<Hit> hits = List.of(
                new Hit("/api/orders", 1024),
                new Hit("/api/orders", 4096),
                new Hit("/health", 64),
                new Hit("/health", 128),
                new Hit("/api/orders", 512));

        // summarizingLong:每个路由一次遍历拿到 count/sum/min/avg/max
        Map<String, LongSummaryStatistics> byRoute = hits.stream()
                .collect(Collectors.groupingBy(Hit::route,
                        Collectors.summarizingLong(Hit::bytes)));

        byRoute.forEach((route, s) -> System.out.printf(
                "%s: count=%d sum=%d min=%d avg=%.1f max=%d%n",
                route, s.getCount(), s.getSum(), s.getMin(), s.getAverage(), s.getMax()));

        // LongSummaryStatistics 也能当累加器手动喂值:跨批次合并
        LongSummaryStatistics merged = new LongSummaryStatistics();
        byRoute.values().forEach(merged::combine);
        System.out.println("merged sum: " + merged.getSum());
    }
}

A walking tour of the code

All of the logic lives in the classes TrafficRollup and Hit and the function main.

The pipeline is a stream: source, lazy intermediate steps, one terminal collector.

Caveats

  • No installation is needed; the snippet works purely with the standard library.

Applying it

The entry-point signature is public static void main(String[] args)

The run emits 1 labeled section — merged sum: — one per step.

Statements that matter

.collect(Collectors.groupingBy(Hit::route,
        Collectors.summarizingLong(Hit::bytes)));

Interactive Tools for This Topic

FAQ

What does LongSummaryStatistics Grouped Rollup print when run?
Running the file directly is enough — expect labeled output lines such as `merged sum:`.