Question 5
Back to Exercise
What is the output of the following Java program?
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
public class Main {
public static void main(String[] args) {
PriorityQueue<String> pq = new PriorityQueue<>(
Comparator.comparing(String::length).thenComparing(Comparator.reverseOrder()));
pq.addAll(List.of("fig", "kiwi", "apple", "date", "pear"));
StringBuilder sb = new StringBuilder();
while (!pq.isEmpty()) sb.append(pq.poll()).append(' ');
System.out.println(sb.toString().trim());
}
}
- A fig date kiwi pear apple
- B apple pear kiwi date fig
- C fig kiwi date pear apple
- D fig pear kiwi date apple Correct
Correct Answer: Option D
Shortest first; the three 4-letter words come out in reverse alphabetical order.
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!