ProgrammingHardProduct-company placement · Java

What is printed?

What is printed?
Map<Integer, String> m = Stream.of("ab", "cd", "e")
    .collect(Collectors.toMap(String::length, s -> s));
System.out.print(m);
  1. A. {2=cd, 1=e}
  2. B. {2=ab, 1=e}
  3. C. {1=e, 2=abcd}
  4. D. An IllegalStateException is thrown (duplicate key 2)

Correct answer: D. An IllegalStateException is thrown (duplicate key 2)

Collectors.toMap without a merge function throws IllegalStateException when two elements map to the same key. Passing a third argument such as (x, y) -> x resolves collisions.

More OOP with C++ and Java questions

Exams that ask this topic