ProgrammingHardAmazon/Microsoft SDE MCQ · Java placement

What is printed?

What is printed?
List<String> l = new ArrayList<>(List.of("pear", "fig", "apple", "kiwi"));
l.sort(Comparator.comparing(String::length).thenComparing(Comparator.reverseOrder()));
System.out.print(l);
  1. A. [fig, kiwi, pear, apple]
  2. B. [fig, pear, kiwi, apple]
  3. C. [apple, pear, kiwi, fig]
  4. D. [fig, pear, apple, kiwi]

Correct answer: B. [fig, pear, kiwi, apple]

The primary key is length (3, 4, 4, 5). The tie between the 4-letter words is broken by reverse natural order, so pear comes before kiwi: [fig, pear, kiwi, apple].

More OOP with C++ and Java questions

Exams that ask this topic