summingInt vs map().sum() Performance Comparison
You'll learn when to prefer Collectors.summingInt() over primitive stream operations and vice versa.
Two Paths to the Same Sum
You've learned summingInt() as a downstream collector, but you've also seen mapToInt().sum() as a way to sum values. They both compute sums, but their contexts and performance characteristics differ.
The Core Difference
Collectors.summingInt() is designed for use inside other collectors (like groupingBy). It produces a Collector<T, ?, Integer> that accumulates sums while building a larger structure:
// Summing within groups
Map<String, Integer> totalsByCategory = products.stream()
.collect(groupingBy(Product::getCategory,
summingInt(Product::getPrice)));
mapToInt().sum() is a direct terminal operation on primitive streams. It's simpler and more efficient when you just want a single sum:
// Direct sum - no grouping, just a total
int total = products.stream()
.mapToInt(Product::getPrice)
.sum();
Performance Insights
For a single sum calculation, mapToInt().sum() is faster because:
- It uses primitive
intoperations (no boxing) - It's a direct terminal operation with less overhead
- No collector infrastructure needed
For grouped sums or nested operations, summingInt() is the right tool because:
- It integrates seamlessly with
groupingByandpartitioningBy - It's designed to work as part of collector pipelines
- Using
map().sum()here would require manual map construction
The Rule of Thumb
Think of mapToInt().sum() as a direct route and summingInt() as a building block. If you just need a sum, take the direct route. If you're building a complex collection structure, use the collector.
Key Takeaway:
Use mapToInt().sum() for simple, direct sums; use Collectors.summingInt() as a downstream collector when aggregating within groups or partitions.