ProgrammingModerateProduct-company placement · Java

What is printed?

What is printed?
Map<Character, Integer> f = new TreeMap<>();
for (char c : "banana".toCharArray()) f.merge(c, 1, Integer::sum);
System.out.print(f);
  1. A. {b=1, a=3, n=2}
  2. B. {a=3, b=1, n=2}
  3. C. {a=1, b=1, n=1}
  4. D. {a=3, n=2, b=1}

Correct answer: B. {a=3, b=1, n=2}

merge inserts 1 for a new key and otherwise combines old and new with Integer::sum, counting each letter. A TreeMap prints its keys in sorted order, not insertion order.

More OOP with C++ and Java questions

Exams that ask this topic