ProgrammingHardProduct-company placement · Java

What is printed?

What is printed?
PriorityQueue<String> pq = new PriorityQueue<>(
    Comparator.comparing(String::length).thenComparing(Comparator.reverseOrder()));
pq.addAll(List.of("bb", "a", "ccc", "aa", "c"));
StringBuilder sb = new StringBuilder();
while (!pq.isEmpty()) sb.append(pq.poll()).append(' ');
System.out.print(sb.toString().trim());
  1. A. c a bb aa ccc
  2. B. a c aa bb ccc
  3. C. ccc bb aa c a
  4. D. c a aa bb ccc

Correct answer: A. c a bb aa ccc

poll() always removes the least element under the comparator: shorter strings first, and among equal lengths reverse alphabetical order (c before a, bb before aa).

More OOP with C++ and Java questions

Exams that ask this topic