Java 8 FAQ: Top Questions
18. How does the reduce() method work in Java 8 Streams?
The reduce()
method is a terminal operation in Java 8 that combines all elements of a stream into a single result using a binary operation. Itβs commonly used for summing numbers, concatenating strings, or computing aggregates.
πΊοΈ Step-by-Step Instructions:
- Define a binary operation using a lambda or method reference.
- Apply
reduce()
with or without an identity value. - With an identity: returns a concrete value. Without identity: returns an
Optional
.
π₯ Example Input:
List numbers = Arrays.asList(1, 2, 3, 4, 5);
π Using reduce() to sum values:
int sum = numbers.stream()
.reduce(0, (a, b) -> a + b);
β Java 8 Solution:
import java.util.*;
import java.util.stream.*;
public class StreamReduceExample {
public static void main(String[] args) {
List numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
.reduce(0, Integer::sum);
System.out.println("Sum: " + sum);
}
}
π Detailed Explanation:
- reduce(identity, accumulator): Applies a binary operation starting with a base value.
- reduce(accumulator): Returns an
Optional
in case the stream is empty. - Works best when converting streams into a single result like sum, product, max, or string join.
π οΈ Use Cases:
- Calculating total, product, or max values from a list.
- Concatenating string values from a stream of words.
- Implementing custom aggregation logic over data.