Senior
What does the reduce method do?
sobes.tech AI
Answer from AI
The reduce method in Java is used for sequentially processing stream elements with accumulation of the result. It takes two parameters:
- An accumulator (bi-function) that combines the current accumulated result and the next element;
- (optionally) an initial value for the accumulator.
Ultimately, reduce reduces a stream of elements to a single value, such as a sum, product, or concatenation.
Example of summing numbers using reduce:
import java.util.Arrays;
import java.util.List;
public class ReduceExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
.reduce(0, (acc, x) -> acc + x);
System.out.println("Sum: " + sum); // Outputs Sum: 15
}
}
If the initial value is not specified, reduce returns an Optional<T>, since the stream may be empty.