Exam 1Z0-809: Java SE 8 Programmer II

Java SE 8 Programmer II

Question

Given: IntStream stream = IntStream.of (1,2,3); IntFunction<Integer> inFu= x -> y -> x*y;//line n1 IntStream newStream = stream.map(inFu.apply(10)); //line n2 newStream.forEach(System.output::print); Which modification enables the code fragment to compile?

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D.

B.

The code given tries to create a new stream newStream from an existing IntStream stream by using an IntFunction<Integer> inFu to perform a mapping operation on each element of stream. The inFu function is not defined correctly, hence the code doesn't compile.

Let's go through each of the given answer choices and see which modification enables the code fragment to compile:

A. Replace line n1 with: IntFunction<UnaryOperator> inFu = x -> y -> x*y;

This modification doesn't work because UnaryOperator is a functional interface that takes one parameter and returns a result of the same type. However, in this case, inFu needs to take an integer and return a function that takes an integer and returns an integer. So, this modification is incorrect.

B. Replace line n1 with: IntFunction<IntUnaryOperator> inFu = x -> y -> x*y;

This modification works because IntUnaryOperator is a functional interface that takes one integer and returns an integer. It is appropriate for use with the map method of the IntStream class. The inFu function returns an IntUnaryOperator that takes an integer y and returns the product of x and y. This allows inFu to be used with the map method to create the new stream newStream.

C. Replace line n1 with: BiFunction<IntUnaryOperator> inFu = x -> y -> x*y;

This modification doesn't work because BiFunction is a functional interface that takes two parameters and returns a result. However, in this case, inFu needs to take one integer and return a function that takes an integer and returns an integer. So, this modification is incorrect.

D. Replace line n2 with: IntStream newStream = stream.map(inFu.applyAsInt(10));

This modification doesn't work because the applyAsInt method of IntFunction takes an integer and returns an integer. However, in this case, inFu needs to return an IntUnaryOperator that takes an integer and returns an integer. So, this modification is incorrect.

Therefore, the correct answer is B: Replace line n1 with: IntFunction<IntUnaryOperator> inFu = x -> y -> x*y;