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));
F.
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.