The reduce()
method in Java Streams is used to perform aggregation operations like summing, finding the minimum or maximum, concatenation, etc. It reduces a stream to a single value.
1. Syntax of reduce()
reduce()
has three main variations:
1. Identity + Accumulator
T reduce(T identity, BinaryOperator accumulator);
- Identity → Initial value
- Accumulator → Operation to combine elements
2. Accumulator Only (Returns Optional)
Optional reduce(BinaryOperator accumulator);
- No identity → returns Optional (empty if stream is empty).
3. Identity + Accumulator + Combiner (for Parallel Streams)
<U> U reduce(U identity, BiFunction<U, T, U> accumulator, BinaryOperator<U> combiner);
- Used in parallel processing.
- Combiner merges results from multiple threads.
2. Examples of reduce()
Usage
Example 1: Sum of Numbers
import java.util.Arrays;
import java.util.List;
public class ReduceExample {
public static void main(String[] args) {
List numbers = Arrays.asList(10, 20, 30, 40);
int sum = numbers.stream()
.reduce(0, (a, b) -> a + b); // Identity = 0, Summation
System.out.println("Sum: " + sum);
}
}
Output:
Sum: 100
Example 2: Find Maximum Value
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class ReduceMaxExample {
public static void main(String[] args) {
List numbers = Arrays.asList(3, 7, 2, 8, 6);
Optional max = numbers.stream()
.reduce((a, b) -> a > b ? a : b); // No identity, returns Optional
max.ifPresent(m -> System.out.println("Max Value: " + m));
}
}
Output:
Max Value: 8
Example 3: Concatenate Strings
import java.util.Arrays;
import java.util.List;
public class ReduceStringExample {
public static void main(String[] args) {
List words = Arrays.asList("Java", "Streams", "Reduce");
String result = words.stream()
.reduce("", (a, b) -> a + " " + b).trim();
System.out.println("Concatenated String: " + result);
}
}
Output:
Concatenated String: Java Streams Reduce
Example 4: Multiplication Using Parallel Streams
import java.util.Arrays;
import java.util.List;
public class ReduceParallelExample {
public static void main(String[] args) {
List numbers = Arrays.asList(2, 3, 4, 5);
int product = numbers.parallelStream()
.reduce(1, (a, b) -> a * b, (a, b) -> a * b); // Combiner required for parallel
System.out.println("Product: " + product);
}
}
Output:
Product: 120
Key Points
- If identity is given, the result is always a non-null value.
- If identity is not given, it returns
Optional<T>
to handle empty streams. - Parallel streams need a combiner to merge partial results efficiently.