LearnFrenzy
Sign in Take a free test

HashMap and TreeMap · Predict the Output · Question 15

A TreeMap ordered by a custom comparator Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 15 Back to Exercise

What is the output of the following Java program?

Main.java
import java.util.Comparator;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        TreeMap<String, Integer> byLen = new TreeMap<>(Comparator.comparing(String::length).thenComparing(Comparator.naturalOrder()));
        for (String s : new String[]{"kiwi", "fig", "banana", "plum", "apple"}) byLen.put(s, s.length());
        TreeMap<Integer, String> desc = new TreeMap<>(Comparator.reverseOrder());
        desc.put(1, "a"); desc.put(3, "c"); desc.put(2, "b");
        System.out.println(byLen.keySet() + " " + desc + " " + desc.firstKey());
    }
}
  • A [fig, kiwi, plum, apple, banana] {3=c, 2=b, 1=a} 3 Correct
  • B [apple, banana, fig, kiwi, plum] {1=a, 2=b, 3=c} 1
  • C [fig, plum, kiwi, apple, banana] {3=c, 2=b, 1=a} 3
  • D [fig, kiwi, plum, apple, banana] {3=c, 2=b, 1=a} 1
Correct Answer: Option A

The comparator decides the key order; with reverseOrder, firstKey is the largest number.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links