Java Stream reduce() Method

The reduce() method in Java, part of the java.util.stream.Stream interface, is a terminal operation that performs a reduction on the elements of the stream using an associative accumulation function and returns an Optional describing the reduced value. This method is particularly useful for combining stream elements into a single result, such as computing the sum, product, or concatenation of elements.

Table of Contents

  1. Introduction
  2. reduce() Method Syntax
  3. Understanding reduce()
  4. Examples
    • Basic Usage
    • Using reduce() with Initial Value
    • Using reduce() with BinaryOperator and Combiner
  5. Real-World Use Case
  6. Conclusion

Introduction

The reduce() method is used to perform a reduction on the elements of the stream using an associative accumulation function. This method comes in three overloaded forms to handle different reduction scenarios.

reduce() Method Syntax

1. Using a BinaryOperator

Optional<T> reduce(BinaryOperator<T> accumulator)

2. Using an Identity and BinaryOperator

T reduce(T identity, BinaryOperator<T> accumulator)

3. Using an Identity, BiFunction, and BinaryOperator

<U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner)

Parameters:

  • identity: The identity value for the reduction (initial value).
  • accumulator: A function that combines two values.
  • combiner: A function that combines two partial results.

Returns:

  • An Optional<T> describing the result of the reduction (for the first form).
  • The result of the reduction (for the second and third forms).

Throws:

  • This method does not throw any exceptions.

Understanding reduce()

The reduce() method allows you to combine elements of a stream into a single result. The method is associative, meaning the order in which operations are performed does not change the result. This makes it suitable for parallel processing.

Examples

Basic Usage

To demonstrate the basic usage of reduce(), we will create a Stream of integers and use reduce() to compute their sum.

Example

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

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

        // Use reduce() to compute the sum of the elements
        Optional<Integer> sum = stream.reduce(Integer::sum);

        // Print the sum if present
        sum.ifPresent(System.out::println);
    }
}

Output:

15

Using reduce() with Initial Value

This example shows how to use reduce() with an initial value to compute the product of the elements.

Example

import java.util.stream.Stream;

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

        // Use reduce() with an initial value to compute the product of the elements
        int product = stream.reduce(1, (a, b) -> a * b);

        // Print the product
        System.out.println(product);
    }
}

Output:

120

Using reduce() with BinaryOperator and Combiner

This example shows how to use reduce() with a custom accumulator and combiner to concatenate strings with parallel processing.

Example

import java.util.stream.Stream;

public class ReduceWithCombinerExample {
    public static void main(String[] args) {
        Stream<String> stream = Stream.of("A", "B", "C", "D", "E");

        // Use reduce() with an identity, accumulator, and combiner to concatenate strings
        String result = stream.parallel().reduce(
            "", // Identity
            (s1, s2) -> s1 + s2, // Accumulator
            (s1, s2) -> s1 + s2 // Combiner
        );

        // Print the result
        System.out.println(result);
    }
}

Output:

ABCDE

Real-World Use Case

Aggregating Sales Data

In real-world applications, the reduce() method can be used to aggregate sales data, such as computing the total sales amount.

Example

import java.util.stream.Stream;

public class ReduceRealWorldExample {
    static class Sale {
        String item;
        double amount;

        Sale(String item, double amount) {
            this.item = item;
            this.amount = amount;
        }

        double getAmount() {
            return amount;
        }
    }

    public static void main(String[] args) {
        Stream<Sale> sales = Stream.of(
            new Sale("Item1", 100.0),
            new Sale("Item2", 200.0),
            new Sale("Item3", 300.0)
        );

        // Use reduce() to compute the total sales amount
        double totalSales = sales.reduce(
            0.0, // Identity
            (sum, sale) -> sum + sale.getAmount(), // Accumulator
            Double::sum // Combiner
        );

        // Print the total sales amount
        System.out.println("Total Sales: " + totalSales);
    }
}

Output:

Total Sales: 600.0

Conclusion

The Stream.reduce() method is used to perform a reduction on the elements of the stream using an associative accumulation function. This method comes in three overloaded forms to handle different reduction scenarios. By understanding and using this method, you can efficiently manage and process streams of values in your Java applications, combining elements into a single result as needed.

Comments