Java SE 8 Programmer II — Question 123

Given the code fragment:
public class Foo {
public static void main (String [ ] args) {
Map<Integer, String> unsortMap = new HashMap< > ( );
unsortMap.put (10, "z");
unsortMap.put (5, "b");
unsortMap.put (1, "d");
unsortMap.put (7, "e");
unsortMap.put (50, "j");
Map<Integer, String> treeMap = new TreeMap <Integer, String> (new
Comparator<Integer> ( ) {
@Override public int compare (Integer o1, Integer o2) {return o2.compareTo
(o2); } } );
treeMap.putAll (unsortMap);
for (Map.Entry<Integer, String> entry : treeMap.entrySet () ) {
System.out.print (entry.getValue () + " ");
}
}
}
What is the result?

Answer options

Correct answer: D

Explanation

The correct answer is D because the TreeMap is using a comparator that incorrectly compares the elements, leading to a sorting based on the natural order of keys in descending order. As a result, the elements are printed in the order of their values based on the sorted keys of the original unsorted map. The other options do not reflect the correct ordering or contain a compilation error.