Quiz W2: Comparators and the compare Contract
Where you are: Comparator and lambdas > Week 1 milestone check
This is a short consolidation check on the Week 1 core: writing a Comparator as a lambda, reading the sign that compare returns, chaining orders with thenComparing, and telling a Comparator apart from the compareTo method on the object itself.
It is low-stakes. If a question stumps you, the matching lesson covers it: compare returns a sign, writing a Comparator as a lambda, and multi-key ordering with thenComparing. Answer each from memory first, then reveal it.
Check Yourself
Check your understanding
True or False: if a Comparator<String> returns a negative integer from compare(a, b), then a should come BEFORE b in ascending order.
True or False: a class that implements Comparable<T> can have only one natural ordering, but you can supply many different orderings for that class by writing separate Comparator objects.
Given: List<String> words = new ArrayList<>(List.of(“banana”, “apple”)); words.sort((a, b) -> a.compareTo(b)); System.out.println(words); What does it print?
Complete the Comparator so it orders strings by length, shortest first (ties may go either way): Comparator<String> byLength = (a, b) -> ____ ;
When you chain two comparators with thenComparing, what happens when the FIRST comparator returns 0 for a pair of elements?