Java SE 8 Programmer II Exam: Stream Interface Methods for Reduction Operation

Java SE 8 Programmer II Exam

Question

Which two methods from the java.util.stream.Stream interface perform a reduction operation? (Choose two.)

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D. E.

AB.

https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html

The correct answers are B. collect() and A. count().

A reduction operation combines all elements of a stream into a single result, and the Stream interface provides several methods to perform reduction operations.

Here is a brief explanation of each method listed in the question and whether it performs a reduction operation:

A. count(): This method returns the count of elements in the stream. It does not perform a reduction operation, as it only returns a single value.

B. collect(): This method performs a mutable reduction operation on the elements of the stream, using a Collector to accumulate the elements into a result container. This method can be used to produce a variety of different results, including lists, sets, and maps.

C. distinct(): This method returns a stream consisting of the distinct elements of the original stream. It does not perform a reduction operation, as it only returns a new stream.

D. peek(): This method returns a stream consisting of the same elements as the original stream, but with an additional action performed on each element as they are consumed from the resulting stream. It does not perform a reduction operation, as it only returns a new stream.

E. filter(): This method returns a stream consisting of the elements of the original stream that match a given predicate. It does not perform a reduction operation, as it only returns a new stream.

In summary, the two methods from the java.util.stream.Stream interface that perform a reduction operation are collect() and count().