Junior — Middle
How does the reduce method differ from the traditional use of loops for processing collections?
sobes.tech AI
Answer from AI
The reduce method in Java (more often through the Stream API) allows you to reduce a collection to a single value by applying an accumulator function. Unlike traditional loops, reduce:
- Is more declarative: it describes what needs to be done, not how.
- Enables writing more concise and readable code.
- Works well with functional style and parallel processing.
Example of summing list elements using reduce:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4);
int sum = numbers.stream()
.reduce(0, (acc, n) -> acc + n);
System.out.println(sum); // 10
In a traditional loop, it would look like this:
int sum = 0;
for (int n : numbers) {
sum += n;
}
System.out.println(sum); // 10
Thus, reduce helps express the logic of collection folding more functionally and concisely.