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

Common reduce Patterns: Sum, Product, Min, Max

Practical examples of reduce for summing numbers, multiplying values, and finding minimum or maximum elements.

Common reduce Patterns: Sum, Product, Min, Max

You'll learn how to apply reduce to solve common aggregation problems like summing numbers, multiplying values, and finding minimums or maximums.

The Core Idea

While reduce is a general-purpose folding operation, certain patterns appear so frequently that they're worth memorizing. Calculating totals, products, and extremes are textbook examples where reduce shines. Each follows the same template: provide an identity value and a binary operation that combines two elements.

Sum Pattern

To sum all elements, use 0 as the identity (adding zero doesn't change values) and addition as the operation:

List<Integer> numbers = List.of(1, 2, 3, 4, 5);
int sum = numbers.stream()
                 .reduce(0, (a, b) -> a + b);
// Result: 15

Product Pattern

For multiplication, use 1 as the identity (multiplying by one doesn't change values):

int product = numbers.stream()
                     .reduce(1, (a, b) -> a * b);
// Result: 120 (1×2×3×4×5)

Min and Max Patterns

Finding the minimum or maximum requires choosing an appropriate identity. For min, use Integer.MAX_VALUE; for max, use Integer.MIN_VALUE:

int min = numbers.stream()
                 .reduce(Integer.MAX_VALUE, (a, b) -> a < b ? a : b);
// Result: 1

int max = numbers.stream()
                 .reduce(Integer.MIN_VALUE, (a, b) -> a > b ? a : b);
// Result: 5

You can also use Math.min and Math.max with method references:

int min = numbers.stream().reduce(Integer.MAX_VALUE, Math::min);
int max = numbers.stream().reduce(Integer.MIN_VALUE, Math::max);

The Pattern

Notice the recipe: identity + operation. Sum uses 0 and addition. Product uses 1 and multiplication. Min/max use extreme values and comparison logic.

Key Takeaway: The four classic reduce patterns—sum (0, +), product (1, ×), min (MAX_VALUE, smaller), and max (MIN_VALUE, larger)—cover most basic aggregation needs in stream processing.