Java OCA OCP Practice Question 1697

Question

How many of these collectors can fill in the blank to make this code compile?

Stream<Character> chars = Stream.of('o', 'b', 's', 't', 'a', 'c', 'l', 'e');
chars.map(c -> c).collect(Collectors.___);
  • I. toArrayList()
  • II. toList()
  • III. toMap()
  • A. None
  • B. One
  • C. Two
  • D. Three


B.

Note

Since the result of the collect() is not stored in a variable or used in any way, all the code needs to do is compile.

There is no Collectors.toArrayList() method.

If you want to specify an ArrayList, you can call Collectors.toCollection(ArrayList::new).

The Collectors.toList() method does in fact exist and compile.

While there is a Collectors.toMap() method, it requires two parameters to specify the key and value functions, respectively.

Since only one can compile, Option B is correct.




PreviousNext

Related