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);- A. [apple, date, kiwi, pear, fig]
- B. [apple, pear, kiwi, date, fig]
- C. [fig, date, kiwi, pear, apple]
- 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
- What is printed? java // static methods of the main class: static void f(Object o) { System.out.print("Object"); } static void f(String s)…
- What is printed? java // static method of the main class: static void f(Object... a) { System.out.print(a == null ? "N " : a.length + "…
- What is printed? java interface Shape { double area(); } class Sq implements Shape { double area() { return 4; } } // in main: Shape s =…
- Which declaration is LEGAL inside an abstract Java class?
- Which line fails to compile? java class Outer { int x = 1; class In { int get() { return x; } } static class SN { int get() { return 2; }…
- What is printed? java class Outer { int x = 1; class Inner { int x = 2; void show(int x) { System.out.print(x + " " + this.x + " " +…