Junior — Middle
Have you used the reduce method in Java for processing collections?
sobes.tech AI
Answer from AI
Yes, the reduce method in Java is used for sequentially processing elements of a collection to reduce them to a single result. It is commonly used with streams (Streams API).
Example: summing numbers in a list:
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, (subtotal, element) -> subtotal + element);
System.out.println("Sum: " + sum); // Outputs: Sum: 15
}
}
The reduce method takes an initial value and an accumulator function that combines elements sequentially.