ProgrammingVery hardProduct-company placement · Java

What is printed?

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

Correct answer: A. [apple, date, kiwi, pear, fig]

reversed() is applied BEFORE thenComparing, so only the length order is reversed (longest first) and ties are broken alphabetically: date, kiwi, pear. Calling reversed() at the end would reverse the tie-break too.

More OOP with C++ and Java questions

Exams that ask this topic