nerdexam
Oracle

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…

Working with Streams and Lambda Expressions

Question

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?

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)
  • A
    3% (1)
  • B
    5% (2)
  • C
    82% (32)
  • D
    10% (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> extends Function<T,T>, not the reverse, so a raw Function cannot satisfy the UnaryOperator<String> parameter.
  • B - UnaryOperator without the type parameter is a raw type, which means the lambda parameter s is inferred as Object; Object has no toUpperCase() method, causing a compile error inside the lambda itself.
  • D - Although Function<String, String> and UnaryOperator<String> share the same functional signature, Java uses nominal (name-based) typing, not structural typing. A Function<String, String> variable is not a subtype of UnaryOperator<String>, so passing it to replaceAll fails 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

#Functional Interfaces#Method References#Generics#Lambda Expressions

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice