Sobes.tech
Junior — Middle

Can you give an example of how to use the reduce method in Stream API for data processing?

sobes.tech AI

Answer from AI

The reduce method in the Stream API is used to fold the elements of a stream into a single value by applying a binary operation. For example, to calculate the sum of 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, (a, b) -> a + b);
        System.out.println("Sum: " + sum);
    }
}

Here, 0 is the initial value of the accumulator, and (a, b) -> a + b is the function that sums two numbers.

Can you give an example of how to use the reduce… - sobes.tech