Question 15
Back to Exercise
What is the output of the following Java program?
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!