nerdexam
Oracle

1Z0-819 · Question #22

Given: ``java List<String> list = ...; list.forEach(x -> { System.out.println(x); }); `` What is the type of x?

The correct answer is C. String. x is inferred as String because forEach on a List<String> accepts a Consumer<String>, so the lambda parameter automatically takes the element type of the list - String in this case. Option A (char) is wrong because Java generics work with objects, not primitives, and char is…

Working with Streams and Lambda Expressions

Question

Given:
List<String> list = ...;
list.forEach(x -> { System.out.println(x); });
What is the type of x?

Options

  • Achar
  • BList<Character>
  • CString
  • DList<String>

How the community answered

(23 responses)
  • A
    9% (2)
  • B
    4% (1)
  • C
    78% (18)
  • D
    9% (2)

Explanation

x is inferred as String because forEach on a List<String> accepts a Consumer<String>, so the lambda parameter automatically takes the element type of the list - String in this case. Option A (char) is wrong because Java generics work with objects, not primitives, and char is neither the element type nor a valid generic type argument. Option B (List<Character>) confuses the container with the element - forEach iterates over the list, giving you each element, not another list. Option D (List<String>) makes the same mistake at a higher level: the variable list is a List<String>, but x is a single element pulled out of it during iteration. Memory tip: The lambda parameter in forEach always mirrors the generic type parameter of the collection - List<T>x is T.

Topics

#lambda expressions#type inference#generics#collections

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice