Find Sum and Average Using Streams in Java
Problem
An IntStream is a stream of primitive ints; unlike a Stream of Integer objects it offers ready-made numeric operations such as sum, average, min and max.
Given a list of exam scores, compute their sum and their average.
Java Program
import java.util.Arrays;
import java.util.List;
public class SumAndAverageStream {
public static void main(String[] args) {
List<Integer> scores = Arrays.asList(72, 88, 95, 61, 84);
int sum = scores.stream()
.mapToInt(Integer::intValue) // unbox to an IntStream, which has sum() and average()
.sum();
double average = scores.stream()
.mapToInt(Integer::intValue)
.average() // OptionalDouble: empty if the list is empty
.orElse(0.0);
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);
}
}Output
Core Logic
Converting the Stream of Integer into an IntStream unlocks numeric terminal operations, so totals need no manual loop or accumulator.
- 1
mapToInt(Integer::intValue)unboxes eachIntegerinto a primitiveint. - 2
sum()adds the values and returns anint. - 3
average()returns anOptionalDouble, because an empty list has no average. - 4
orElse(0.0)supplies a fallback for the empty case.
Key Point: A stream can only be consumed once, which is why the code calls scores.stream() twice — reusing the first stream would throw IllegalStateException.
Why: Each pipeline makes one pass with a running total; this version makes two passes, still linear.
Key Concepts
Approach 2: Using IntSummaryStatistics
import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
public class SumAndAverageStatistics {
public static void main(String[] args) {
List<Integer> scores = Arrays.asList(72, 88, 95, 61, 84);
IntSummaryStatistics stats = scores.stream()
.mapToInt(Integer::intValue)
.summaryStatistics(); // one pass collects count, sum, min, max and average
System.out.println("Count: " + stats.getCount());
System.out.println("Sum: " + stats.getSum());
System.out.println("Min: " + stats.getMin());
System.out.println("Max: " + stats.getMax());
System.out.println("Average: " + stats.getAverage());
}
}
Output
Core Logic
When you need several statistics, summaryStatistics() computes all of them in a single pass.
- 1
summaryStatistics()is the terminal operation on theIntStream. - 2The returned object exposes
getCount,getSum,getMin,getMaxandgetAverage. - 3For an empty stream it returns sensible defaults (count 0, average 0.0) instead of an
Optional.
Key Point: This is the efficient choice for dashboards and reports, where you'd otherwise stream the same list four or five times.
Why: A single pass updates five running values.
Key Concepts
Interview Questions
Why does average() return an OptionalDouble?
An empty stream has no average, so the result may be absent. orElse(0.0) or getAsDouble() gets the value out.
How do you sum a field of objects?
list.stream().mapToInt(Item::getQuantity).sum(), or Collectors.summingInt(Item::getQuantity) inside a collector.