Course contentsShow
← Java
Lesson 1507 of 2,87033. Streams API: Terminal OperationsFree lesson

Identity Element Requirements: Associativity and Neutrality

Why the identity must satisfy identity op x = x for all x, ensuring correct parallel and sequential results.

Identity Element Requirements: Associativity and Neutrality

You'll learn why the identity value in reduce must be truly neutral to guarantee correct results in both sequential and parallel streams.

When you provide an identity element to reduce(identity, accumulator), Java trusts that this value is genuinely neutral—it won't alter any element it's combined with. Specifically, the identity must satisfy: identity op x = x for all elements x in your stream.

Why This Matters

Consider reduce(0, Integer::sum). Zero is a true identity because 0 + x = x for any integer. The operation is also associative: (a + b) + c = a + (b + c). These properties let Java split your stream across multiple threads, compute partial results independently, then combine them—all guaranteed to produce the same answer as sequential processing.

What happens if you violate neutrality?

Imagine incorrectly using reduce(10, Integer::sum) to sum numbers [5, 3, 2]:

  • Sequential: ((10 + 5) + 3) + 2 = 20
  • Parallel (two threads): Thread 1 computes 10 + 5 = 15, Thread 2 computes 10 + 3 + 2 = 15, then combine: 15 + 15 = 30

You get different results! The 10 isn't neutral—it adds extra value in parallel mode because each thread starts with its own copy of the identity.

The Two Requirements

  1. Neutrality: identity op x = x (the identity doesn't change results)
  2. Associativity: (a op b) op c = a op (b op c) (grouping doesn't matter)

Together, these ensure that no matter how Java chunks your data for parallel processing, the final result remains consistent and correct.

Key Takeaway:
Always choose a true identity element that satisfies identity op x = x for all stream elements—this guarantees identical results whether your stream executes sequentially or in parallel.