ProgrammingHardProduct-company placement · Java

What is printed?

What is printed?
Map<String, Integer> m = new HashMap<>();
m.compute("a", (k, v) -> v == null ? 1 : v + 1);
m.compute("a", (k, v) -> v == null ? 1 : v + 1);
m.computeIfPresent("b", (k, v) -> v + 100);
System.out.print(m + " ");
m.compute("a", (k, v) -> null);
System.out.print(m.containsKey("a") + " " + m.size());
  1. A. {a=2} false 0
  2. B. {a=2} true 1
  3. C. {a=2, b=100} false 1
  4. D. {a=1} false 0

Correct answer: A. {a=2} false 0

compute receives the current value (null the first time), so a becomes 1 then 2. computeIfPresent does nothing for a missing key. Returning null from the remapping function removes the mapping.

More OOP with C++ and Java questions

Exams that ask this topic