LearnFrenzy
Sign in Take a free test

Data Structures in Java · Data Structures in Java Output Questions · Question 5

PriorityQueue ordered by length, then reverse text Answer, explanation & discussion

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

What is the output of the following Java program?

Main.java
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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links