What does the reduce() method in the Stream API do?

Java MCQ: What does the reduce() method in the Stream API do?

a) Filters the elements of a stream
b) Combines the elements of a stream into a single result
c) Converts elements of a stream to another type
d) Collects the elements of a stream into a List

Answer:

b) Combines the elements of a stream into a single result

Explanation:

The reduce() method in the Stream API combines the elements of a stream into a single result. It performs a reduction on the elements of the stream using an associative accumulation function, producing a single value.

Here’s an example of using reduce() to sum the elements of a stream:

import java.util.List;

public class StreamReduceExample {
    public static void main(String[] args) {
        List<Integer> numbers = List.of(1, 2, 3, 4, 5);
        int sum = numbers.stream()
                         .reduce(0, Integer::sum);

        System.out.println("Sum: " + sum);
    }
}

In this example, reduce() is used to sum the integers in the numbers list. The method takes two arguments: an initial value (0 in this case) and a binary operator that combines two elements (using Integer::sum). The result is the sum of all the elements, which is printed.

The reduce() method is a powerful tool for performing aggregation operations on streams, such as summing, averaging, or concatenating elements.

Reference links:

https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top