Java OCA OCP Practice Question 2285

Question

What is the output of the following?

Stream<String> s = Stream.of("speak", "bark", "meow", "growl"); 
Map<Integer, String> map = s.collect(toMap(String::length, k -> k)); 
System.out.println(map.size() + " " + map.get(4)); 
  • A. 2 bark
  • B. 2 meow
  • C. 4 bark
  • D. 4 meow
  • E. The output is not guaranteed.
  • F. The code compiles but throws an exception at runtime.


F.

Note

The collector tries to use the number of characters in each stream element as the key in a map.

This works fine for the first two elements, speak and bark, because they are of length 5 and 4, respectively.

When it gets to meow, we have a problem because the length 4 is already used.

Java requires a merge function be passed to toMap() as a third parameter if there are duplicate keys so it knows what to do.

Since this is not supplied, the code throws an IllegalStateException due to the duplicate key, and Option F is correct.




PreviousNext

Related