1Z0-819 · Question #116
Given: // line 1 List<String> fruits = new ArrayList<>(List.of("apple", "orange", "banana"))); fruits.replaceAll(function); Which statement on line 1 enables this code fragment to compile?
The correct answer is C. C. UnaryOperator<String> function = String::toUpperCase. List.replaceAll() is declared as void replaceAll(UnaryOperator<E> operator), so for a List<String> it strictly requires a UnaryOperator<String> - option C provides exactly that, and String::toUpperCase is a valid method reference matching the String → String signature. Why the…
Question
Options
- AA. Function function = String::toUpperCase;
- BB. UnaryOperator function = s -> s.toUpperCase();
- CC. UnaryOperator<String> function = String::toUpperCase;
- DD. Function<String, String> function = m -> m.toUpperCase();
How the community answered
(39 responses)- A3% (1)
- B5% (2)
- C82% (32)
- D10% (4)
Explanation
List.replaceAll() is declared as void replaceAll(UnaryOperator<E> operator), so for a List<String> it strictly requires a UnaryOperator<String> - option C provides exactly that, and String::toUpperCase is a valid method reference matching the String → String signature.
Why the distractors fail:
- A -
Function(raw type) is in a different interface hierarchy:UnaryOperator<T>extendsFunction<T,T>, not the reverse, so a rawFunctioncannot satisfy theUnaryOperator<String>parameter. - B -
UnaryOperatorwithout the type parameter is a raw type, which means the lambda parametersis inferred asObject;Objecthas notoUpperCase()method, causing a compile error inside the lambda itself. - D - Although
Function<String, String>andUnaryOperator<String>share the same functional signature, Java uses nominal (name-based) typing, not structural typing. AFunction<String, String>variable is not a subtype ofUnaryOperator<String>, so passing it toreplaceAllfails at compile time.
Memory tip: Think of replaceAll as "swap each element with a transformed copy of itself" - same type in, same type out - which maps directly to UnaryOperator (one type, one role). Whenever you see replaceAll, reach for UnaryOperator<T>, not Function.
Topics
Community Discussion
No community discussion yet for this question.