Java Stream reduce() Example

1. Introduction

This tutorial covers the reduce() method of the Java Stream API. The reduce() method is used for reducing the elements of a stream to a single value by repeatedly applying a combining operation. It's a powerful tool for aggregating stream data into a summary result.

Key Points

1. The Java Stream reduce() method is a terminal operation that can reduce all elements in the stream to a single element.

2. It takes a binary operator to combine all elements of the stream into a single result.

3. The method can be overloaded; one takes an identity value and a binary operator, another only takes a binary operator and returns an Optional.

2. Program Steps

1. Create a Stream of values.

2. Apply the reduce() method to compute a sum of numbers.

3. Use the reduce() method without an identity value to handle possible empty streams.

4. Use the reduce() method with an identity value and a binary operator to ensure a default result.

3. Code Program

import java.util.Optional;
import java.util.stream.Stream;

public class StreamReduceExample {

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

        // Reduce with BinaryOperator (sum)
        Optional<Integer> sum = numbers.reduce(Integer::sum);
        sum.ifPresent(s -> System.out.println("Sum: " + s));

        // Re-create the stream as it has already been consumed
        numbers = Stream.of(1, 2, 3, 4, 5);

        // Reduce with identity and BinaryOperator (sum)
        int sumWithIdentity = numbers.reduce(0, Integer::sum);
        System.out.println("Sum with identity: " + sumWithIdentity);

        // Empty Stream example
        Stream<Integer> emptyStream = Stream.empty();

        // Reduce empty stream with identity
        int sumOfEmptyStream = emptyStream.reduce(0, Integer::sum);
        System.out.println("Sum of empty stream: " + sumOfEmptyStream);
    }
}

Output:

Sum: 15
Sum with identity: 15
Sum of empty stream: 0

Explanation:

1. Stream.of(1, 2, 3, 4, 5) creates a stream of integers.

2. numbers.reduce(Integer::sum) applies the sum operation across the numbers in the stream, returning an Optional.

3. sum.ifPresent(s -> System.out.println("Sum: " + s)) checks if the sum is present and prints it.

4. numbers.reduce(0, Integer::sum) starts with an identity (0) and applies the sum operation, ensuring a default result even for an empty stream.

5. Stream.empty() creates an empty stream of integers.

6. emptyStream.reduce(0, Integer::sum) demonstrates how the identity value ensures that we get a meaningful result (0 in this case) even when the stream is empty.

Comments