Return to site

JAVA CERTIFICATION QUESTION: The three-argument overload of the Stream API’s reduce method

👉 There are three reduce overloads; you should know what they do.

· java,ocp

Imagine you have the following Person record:

Your colleague wrote the following code to calculate the total experience of all the people in the stream:

To test the code, your colleague used the following test case, which produced a total experience of 15 years:

Which statement is correct? Choose one.

* Line n1 contains an error.

* Line n2 contains an error.

* Both lines n1 and n2 contain errors.

* The code is properly constructed for calculating the total experience.

#java #certificationquestion #ocp

 

 

Answer.

This question investigates the three-argument overload of the reduce method in the Stream API.

The one that interests us is the three arguments one:

javadoc👉 https://lnkd.in/en6AeFT6)

The operation of this three-argument reduction takes an identity value of the result type, rather than the stream type.

It also takes a BiFunction operation that combines a value of the result type with a value of the stream type and produces a new value of the result type.

This works well but has a problem in a parallel configuration of the stream.

In parallel mode, each of the separate threads that work on the reduction produces a partial result derived from just some of the stream’s data.

To get to a final result, these partial results must be combined.

This is the purpose of the third argument, which is a BinaryOperator of the result type.

Let's inspect each of the arguments:

First argument: ok

Second argument: ok

Finally, the third argument: consider the combiner provided on line n2.

This adds up the intermediate sums that might be created in separate threads if the stream were executed in parallel mode.

However, it should be calculating a sum, not a multiplication, so that’s clearly a logical error.

So it would not throw an exception nor cause a compiler error but it will output the wrong result in parallel mode.

So 'Line n2 contains an error.' is the answer.

http://bit.ly/3fmTmVp