nerdexam
Oracle

1Z0-809 · Question #53

unSortMap.put (7, "e"); unSortMap.put (50, "m"); Map<Integer, String> treeMap = new TreeMap <Integer, String> (new Comparator<Integer> () { @Override public int compare (Integer o1, Integer o2)…

The correct answer is C. e z b d. Option C is correct because the custom Comparator uses o2.compareTo(o1) instead of the natural o1.compareTo(o2), which reverses the sort order - TreeMap stores entries by descending key rather than ascending. When iterated, the values are printed from the highest key to the…

Question

unSortMap.put (7, "e"); unSortMap.put (50, "m"); 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?

Options

  • AA compilation error occurs.
  • Bd b e j
  • Ce z b d
  • Dz b d e j

How the community answered

(34 responses)
  • A
    3% (1)
  • B
    6% (2)
  • C
    85% (29)
  • D
    6% (2)

Explanation

Option C is correct because the custom Comparator uses o2.compareTo(o1) instead of the natural o1.compareTo(o2), which reverses the sort order - TreeMap stores entries by descending key rather than ascending. When iterated, the values are printed from the highest key to the lowest, yielding e z b d.

Why the distractors are wrong:

  • A is wrong because the code is syntactically valid Java - anonymous Comparator classes with generics compile without issue.
  • B (d b e j) reflects ascending key order (natural TreeMap behavior without the custom Comparator), not the reversed order the code actually applies.
  • D (z b d e j) contains five values, suggesting a misread of the map's contents or confusion about which entries are included.

Memory tip: When you see o2.compareTo(o1) in a Comparator, mentally swap the letters - o2 before o1 means the second argument wins, which flips to descending order. Think: "backwards arguments, backwards sort."

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice