1Z0-809 · Question #225
Given the code fragment: Map<Integer, Integer> mVal = new HashMap<>(); mVal.put(1, 10); mVal.put(2, 20); //line n1 c.accept(1, 2); mVal.forEach(c); Which statement can be inserted into line n1 to…
The correct answer is A. BiConsumer<Integer, Integer> c = (i,j) -> System.out.print (i + "," + j + " "). Option A is correct because BiConsumer<T, U> is a functional interface with an accept(T, U) method that takes two inputs and returns void - which satisfies both c.accept(1, 2) (prints 1,2) and Map.forEach(c), which expects a BiConsumer<K, V> to receive each key-value pair…
Question
Options
- ABiConsumer<Integer, Integer> c = (i,j) -> System.out.print (i + "," + j + " ");
- BBiFunction<Integer, Integer, String> c = (i,j) ?gt;:(System.out.print (i + "," + j + " "));
- CBiConsumer<Integer, Integer, String> c = (i,j) ?gt;:(System.out.print (i + "," + j + " "));
- DBiConsumer<Integer, Integer> Integer> c = (i,j) ?gt;:(System.out.print (i + "," + j + " "));
How the community answered
(40 responses)- A73% (29)
- B3% (1)
- C8% (3)
- D18% (7)
Explanation
Option A is correct because BiConsumer<T, U> is a functional interface with an accept(T, U) method that takes two inputs and returns void - which satisfies both c.accept(1, 2) (prints 1,2) and Map.forEach(c), which expects a BiConsumer<K, V> to receive each key-value pair (printing 1,10 then 2,20). The lambda (i,j) -> System.out.print(...) is void-returning, which aligns perfectly with BiConsumer.
B is wrong because BiFunction<T, U, R> returns a value (here String), but System.out.print returns void - the types are incompatible; also, Map.forEach requires a BiConsumer, not a BiFunction, and BiFunction uses .apply() not .accept(). C is wrong because BiConsumer only accepts two type parameters - BiConsumer<Integer, Integer, String> with three is not a valid type and will not compile. D is wrong because BiConsumer<Integer, Integer> Integer> is simply malformed syntax - the diamond is closed early, making it a compile error.
Memory tip: Think of the name literally - Bi = two inputs, Consumer = consumes (no return value). Whenever you see Map.forEach, it always wants a BiConsumer<K, V>, and any lambda you pass must be void-returning to match.
Community Discussion
No community discussion yet for this question.