ProgrammingHardProduct-company placement · Java

What is printed?

What is printed?
List<String> l = new ArrayList<>(List.of("ccc", "ee", "a", "bb", "d"));
l.sort(Comparator.comparingInt(String::length));
System.out.print(l);
  1. A. [a, d, bb, ee, ccc]
  2. B. [d, a, ee, bb, ccc]
  3. C. [a, bb, ccc, d, ee]
  4. D. [a, d, ee, bb, ccc]

Correct answer: D. [a, d, ee, bb, ccc]

The comparator looks only at length, so a/d and ee/bb tie. List.sort is guaranteed STABLE, so tied elements keep their original relative order (a before d, ee before bb) instead of being put in alphabetical order.

More OOP with C++ and Java questions

Exams that ask this topic