Java Stream reduce() Example

1. Introduction

The reduce() method in Java Streams API is essential for performing reduction operations, where a sequence of input elements is combined into a single summary result. This method is flexible and powerful, ideal for various aggregative tasks like summing values, finding minimum or maximum, or accumulating elements into a single result.

Key Points

1. reduce() can be used without initial value, with an initial value, or with an initial value and a combiner in parallel processing.

2. It returns an Optional when no initial value is provided to handle the possibility of reducing an empty stream.

3. When an initial value is provided, reduce() returns a direct result of the specified type.

4. In parallel streams, a combiner function is necessary to combine results of reductions from different threads.

2. Program Steps

1. Import the necessary classes.

2. Create several stream examples to demonstrate different uses of reduce().

3. Display each result to demonstrate the outcomes.

3. Code Program

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class StreamReduceExamples {

    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

        // No initial value
        Optional<Integer> sumResult = numbers.stream().reduce((a, b) -> a + b);
        sumResult.ifPresent(sum -> System.out.println("Sum (no initial value): " + sum));

        // With initial value
        Integer sumWithInitial = numbers.stream().reduce(100, (a, b) -> a + b);
        System.out.println("Sum (with initial value): " + sumWithInitial);

        // With initial value and combiner
        Integer parallelSum = numbers.parallelStream().reduce(10,
                (a, b) -> a + b, // accumulator
                (a, b) -> a + b); // combiner
        System.out.println("Parallel sum (with combiner): " + parallelSum);
    }
}

Output:

Sum (no initial value): 15
Sum (with initial value): 115
Parallel sum (with combiner): 70

Explanation:

1. No Initial Value: The reduce() without an initial value returns an Optional, handling cases where the stream might be empty. In this example, it sums 1 + 2 + 3 + 4 + 5 to get 15.

2. With Initial Value: When provided with an initial value, reduce() starts with that value. Here, 100 is added to the sum of all numbers in the list, resulting in 115.

3. Parallel Stream with Combiner: When using reduce() on a parallel stream, a combiner function is also needed. The combiner function combines results from different threads. Starting each thread with a value of 10 and summing across 5 threads (because there are 5 numbers), the starting value accumulates to 50 plus the sum of the numbers 20 equals 70.


Comments