Course contentsShow
← Java
Lesson 1594 of 2,87034. Collectors in DepthFree lesson

Handling Empty Streams with Summing and Averaging Collectors

Understand how summing collectors return 0 and averaging collectors return 0.0 for empty streams.

Handling Empty Streams with Summing and Averaging Collectors

What you'll learn: You'll understand exactly what happens when you apply summing and averaging collectors to streams that contain no elements.

The Core Behavior

When working with streams, you'll often encounter scenarios where your data source might be empty. The summing and averaging collectors handle this gracefully with predictable, sensible defaults:

  • Summing collectors (summingInt, summingLong, summingDouble) return 0 (or 0L, 0.0) for empty streams
  • Averaging collectors (averagingInt, averagingLong, averagingDouble) return 0.0 for empty streams

Think of it like this: if you're adding up the values in an empty collection, the mathematical result is zero. Similarly, the average of "nothing" defaults to zero rather than throwing an exception or returning an Optional.

Why This Matters

This behavior is convenient because:

  1. No null checks needed – you always get a numeric result, never null
  2. Safe for downstream operations – you can immediately use the result in calculations
  3. Consistent with mathematical convention – the sum of an empty set is the additive identity (zero)

Example Scenario

List<Integer> emptyList = List.of();

int sum = emptyList.stream()
    .collect(Collectors.summingInt(x -> x));  // Returns 0

double avg = emptyList.stream()
    .collect(Collectors.averagingInt(x -> x));  // Returns 0.0

This differs from operations like min() or max(), which return an Optional because there's no sensible default for "the smallest of nothing."

Key Takeaway: Summing collectors return 0 and averaging collectors return 0.0 when applied to empty streams, providing safe, predictable results without needing Optional handling.