Result of TreeMap with Custom Comparator in Java | Exam 1Z0-809 | Oracle Certification

The Result of TreeMap with Custom Comparator in Java

Question

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 (o1); }} ); treeMap.putAll (unsortMap); for (Map.Entry<Integer, String> entry : treeMap.entrySet () ) { System.out.print (entry.getValue () + " "); } } } What is the result?

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D.

C.

The given code creates a HashMap named unsortMap and adds five key-value pairs to it. Then, a TreeMap named treeMap is created with a custom Comparator that sorts the keys in reverse order (highest to lowest). The treeMap is then populated with the entries of unsortMap using the putAll() method. Finally, the values of treeMap are printed in the order of their keys using a for-each loop.

The output of the program will be: j z e b d

Here's why:

The TreeMap sorts its keys in reverse order due to the custom Comparator provided in the constructor. So, when the putAll() method is called, the entries of unsortMap are added to treeMap in reverse order of their keys: 50, 10, 7, 5, 1. This means that the output will be in the order of the values corresponding to those keys: j (corresponding to key 50), z (corresponding to key 10), e (corresponding to key 7), b (corresponding to key 5), and d (corresponding to key 1).

Therefore, option C ("j z e b d") is the correct answer.