Java Stream reduce() Method with Examples

Ramesh Fadatare
3 min readSep 26, 2024

--

The reduce() method in Java is a part of the java.util.stream.Stream interface. In this guide, we will learn how to use reduce() method in Java with practical examples and real-world use cases to better understand its functionality.

Learn Java from scratch: Learn Java Programming.

Complete Java Reference: Java API Documentation.

Table of Contents

  1. Introduction
  2. reduce() Method Syntax
  3. Understanding reduce()
  4. Examples
  5. Real-World Use Case
  6. Conclusion

Introduction

The Stream.reduce() method in Java is used to perform a reduction operation on the elements of a stream. It combines the stream elements into a single result by repeatedly applying a binary operation (such as addition, multiplication, or concatenation).

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.

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.

Original Post:

https://www.rameshfadatare.com/java-stream/java-stream-reduce-method/

--

--

No responses yet