← Quiz: Comparable vs Comparator: all 10 questions
Quiz: Comparable vs Comparator · Question 2 of 10
What does this print? (code)
What does this print?
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> w = new ArrayList<>(List.of("kiwi", "fig", "apple", "date"));
w.sort(Comparator.comparingInt(String::length).thenComparing(Comparator.naturalOrder()));
System.out.println(w);
}
}
- A.[apple, date, fig, kiwi]
- B.[fig, date, kiwi, apple]
- C.[fig, kiwi, date, apple]
- D.[kiwi, fig, apple, date]
Answer & explanation
Correct answer: [fig, date, kiwi, apple]
Shortest first (fig = 3), then the two 4-letter words alphabetically (date, kiwi), then apple.
Can you get the rest right without peeking?
Take the timed Quiz: Comparable vs Comparator quiz free. Pass it to earn XP and count towards your certificate.
Start the quiz →