Skip to content
Ameen Abozaid
BEG-032

Sorting and comparison

  • 4 Lessons
  • 40 min of reading
  • 2 h practice (estimate)
On this page 8 topics

Overview

Topics

  • Comparable
  • Comparator
  • sorting collections

Learn first

40 min of reading · 2 h of practice (estimate)

Learning outcomes

  1. Implement Comparable for a natural ordering.
  2. Build Comparators, including multi-key ones with comparing and thenComparing.
  3. Sort lists and use sorted collections (TreeMap, TreeSet) with custom ordering.

Lessons

  1. 01Natural ordering with Comparable10 min read
  2. 02Comparators9 min read
  3. 03Multi-key sorting10 min read
  4. 04Demo: a leaderboard with multi-key comparators11 min read

Lab and exercises

Lab

BEG-032-LAB1 · Leaderboard

Outcomes: 1–3 · Time: ~1 h Sort players by score descending, then name ascending, and show the top N. Also keep players in a TreeSet using the same comparator. Acceptance: ties ordered correctly.

Exercises (assessment: three exercises)

IDOutcomeTask
BEG-032-EX011Make a Book (title, year) implement Comparable<Book> by year; sort a list of books.
BEG-032-EX022, 3Build a comparator for Book: year descending, then title ascending; sort with it.
BEG-032-EX033Put books in a TreeSet using a title comparator. Add two books with the same title and different years; explain the size.
Show solutions
  • EX01 public int compareTo(Book o){ return Integer.compare(year, o.year); } then Collections.sort(books);.
  • EX02 Comparator.comparingInt(Book::getYear).reversed().thenComparing(Book::getTitle).
  • EX03 The set has size 1 for the duplicated title: the comparator returns 0, so the set treats them as the same element. This is why ordering must match what "equal" means for the set.
  • Subtraction-overflow mistake is covered in demo L04 and quiz Q09.

Quiz

Outcomes: O1 Comparable · O2 Comparator · O3 sorting and sorted collections.

A self-check for you: nothing is graded, saved or sent anywhere. Choose an answer, then check it. You can try again as often as you like.

  1. 1Comparable<T> requires which method?O1
  2. 2compareTo returns a positive number when:O1
  3. 3A safe way to compare two ints:O1
  4. 4Comparator.comparing(Player::getName) sorts by:O2
  5. 5To reverse a comparator:O2
  6. 6Use a Comparator rather than Comparable when:O2
  7. 7thenComparing is used to:O3
  8. 8Two elements with compare result 0 in a TreeSet:O3
  9. 9Why is return a - b; risky?O1
  10. 10list.sort(null) or Collections.sort(list) uses:O3

Practical part

Three exercises BEG-032-EX01 to EX03 plus the lab. Pass: all three exercises correct and tied scores ordered by name in the lab.

Common mistakes

Subtraction-based compare (overflow); ordering inconsistent with equals.

Assessment

3 exercises.

Career relevance

Sorting in APIs (JNR-019) and SQL ORDER BY (BEG-050).

Type to search levels, phases, modules and lessons.