Java SE 8 Programmer II — Question 114

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 o1.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: B

Explanation

The correct answer is B, as the TreeMap sorts the entries by their keys. The keys are 1, 5, 7, 10, and 50, which correspond to the values 'd', 'b', 'e', 'z', and 'j' respectively. The other options do not reflect the sorted order of the values based on the integer keys.