🎙 Free live masterclass · Sun, 29 Nov, 7:00 pm IST · Java Full Stack roadmap Register free →
Skills101
← 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);
    }
}
  1. A.[apple, date, fig, kiwi]
  2. B.[fig, date, kiwi, apple]
  3. C.[fig, kiwi, date, apple]
  4. 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 →