← Skill tree CS Skill Tree 0 CSCD211

Quiz W2: Comparators and the compare Contract

Textbook: BJP (Reges and Stepp)

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.

Tier 1 · Java 25 Comparator.compare contract; Competency Map area 3 THEN; BJP (Reges and Stepp), Ch 10

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.

Tier 2 · Java 25 Comparator and Comparable docs; S20 Lab 1 design spec; Competency Map area 3

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?

Tier 2 · S20 Lab 1 comparator usage; BJP (Reges and Stepp), Ch 10 (sorting with a Comparator)

Complete the Comparator so it orders strings by length, shortest first (ties may go either way): Comparator<String> byLength = (a, b) -> ____ ;

Tier 2 · S20 Lab 1 (write a Comparator); BJP (Reges and Stepp), Ch 10 lambda syntax; Competency Map area 3 CORE

When you chain two comparators with thenComparing, what happens when the FIRST comparator returns 0 for a pair of elements?

Tier 3 · Java 25 Comparator.thenComparing docs; BJP (Reges and Stepp), Ch 10; Competency Map area 3 THEN