What is reduce? Folding a Stream into a Single Value
You'll learn what reduce() does as a terminal operation that combines all stream elements into a single result.
The Core Idea
Imagine you have a stream of numbers and want to calculate their sum, or a stream of strings you want to concatenate. The reduce() operation takes a stream of many elements and "folds" or "reduces" them down to a single value by repeatedly applying a combining function.
Think of it like folding a long piece of paper: you take two adjacent sections, combine them, then take that result and combine it with the next section, repeating until you have one folded piece.
How reduce Works
The reduce() operation requires an associative accumulation function — a function that takes two values and produces one combined value. This function is applied repeatedly:
- Take the first two elements, combine them
- Take that result and combine it with the third element
- Continue until all elements are processed
- Return the final single value
The operation is called "reduce" because you're reducing many values into one.
The Folding Analogy
Picture a stack of papers (your stream elements). You pick up the first two, merge their content onto one sheet, then merge that with the third sheet, and so on. At the end, you have one sheet containing the combined information from all — that's reduction.
The combining function must be associative, meaning (a + b) + c should equal a + (b + c). This property allows parallel streams to reduce efficiently by combining partial results.
Key Takeaway:
reduce() is a terminal operation that collapses a stream into a single value by repeatedly applying an associative combining function to pairs of elements.