1Z0-809 · Question #109
Given: ``java IntStream stream = IntStream.of(1,2,3); IntFunction<Integer> inFu = x -> x * x;//line n1 IntStream newStream = stream.map(inFu.apply(10));//line n2…
The correct answer is B. Replace line n1 with: IntFunction<IntUnaryOperator> inFu = x -> y -> x*y; Replace line n2 with: IntStream newStream = stream.map(inFu.applyAsInt(10)). Option B works because it changes inFu from a function that produces a value into a curried function that produces another function. With IntFunction<IntUnaryOperator>, calling inFu.apply(10) returns y -> 10y - an IntUnaryOperator - which is exactly what IntStream.map()…
Question
IntStream stream = IntStream.of(1,2,3);
IntFunction<Integer> inFu = x -> x * x;//line n1
IntStream newStream = stream.map(inFu.apply(10));//line n2
newStream.forEach(System.out::print);
Which modification enables the code fragment to compile?Options
- AReplace line n1 with: IntFunction<UnaryOperator> inFu = x -> y -> x*y;
- BReplace line n1 with: IntFunction<IntUnaryOperator> inFu = x -> y -> x*y; Replace line n2 with: IntStream newStream = stream.map(inFu.applyAsInt(10));
- CReplace line n2 with: IntStream newStream = stream.map(inFu.applyAsInt(10));
- DReplace line n2 with: IntStream newStream = stream.map(inFu.apply(10));
How the community answered
(17 responses)- A12% (2)
- B82% (14)
- D6% (1)
Explanation
Option B works because it changes inFu from a function that produces a value into a curried function that produces another function. With IntFunction<IntUnaryOperator>, calling inFu.apply(10) returns y -> 10*y - an IntUnaryOperator - which is exactly what IntStream.map() requires. Without this change, the n2 fix alone cannot help because map needs a mapping function, not an integer result.
Option A fails because UnaryOperator (raw/unparameterized) is not an IntUnaryOperator - they are separate functional interfaces, and IntStream.map() specifically requires IntUnaryOperator. Also, n2 is unchanged, so the wrong type is still passed.
Option C fails because IntFunction<Integer> (n1 unchanged) has no applyAsInt method - that method belongs to IntUnaryOperator. This is a compile error on n2 itself before map even comes into play.
Option D fails because with the original IntFunction<Integer>, inFu.apply(10) evaluates to the integer 100, not a function. IntStream.map() can't accept a bare int/Integer where it expects an IntUnaryOperator.
Memory tip: IntStream.map() takes a transformer function (an IntUnaryOperator), never a pre-computed value. If you find yourself calling .apply(n) directly inside map(...), ask "am I passing a function or an already-computed result?" - passing a result means you applied one level too early and need currying.
Community Discussion
No community discussion yet for this question.