Java SE 8 Programmer II — Question 207
Given the code fragment:
Map<Integer, String> books = new TreeMap<>();
books.put (1007, "A");
books.put (1002, "C");
books.put (1001, "B");
books.put (1003, "B");
System.out.println (books);
What is the result?
Answer options
- A. {1007 = A, 1002 = C, 1001 = B, 1003 = B} {1001 = B, 1002 = C, 1003 = B, 1007 = A} B.
- C. {1002 = C, 1003 = B, 1007 = A}
- D. {1007 = A, 1001 = B, 1003 = B, 1002 = C}
Correct answer: D
Explanation
The correct answer is D because TreeMap sorts its entries by the keys in natural order. Thus, when we print the map, it displays the entries in ascending order of keys: 1001, 1002, 1003, and 1007. The other options do not reflect this order correctly.