Command Palette

Search for a command to run...

Back to the lesson: Topic 9.10 — Comparable and Comparator
Core Java · Example 2 of 4 Java 16+

Comparator.comparing, thenComparing and reverseOrder

Comparator.comparing and thenComparing are Java 8; the record needs Java 16.

Comparable gives a class one built-in natural order (compareTo), and a Comparator is a separate object that describes any other order. Sorting, TreeMap, TreeSet, PriorityQueue, min and max all work through one of the two.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Sort a list of words by length, shortest first, and alphabetically among words of the same length.

02

Write a Version record (major, minor, patch) that implements Comparable so 1.10.0 sorts after 1.9.3.

03

Given a Map<String, Integer> of word counts, print the entries sorted by count descending, then by word.

Explain it without notes

01

When would you implement Comparable, and when would you write a Comparator instead?

02

Why is (a, b) -> a - b a dangerous comparator, and what should you use?

03

Explain what "consistent with equals" means and what goes wrong in a TreeSet when it isn't.

04

Why does it matter that Java's object sort is stable? Give a concrete example.

Comparator.comparing, thenComparing and reverseOrder Java 16+
Sign in to run this example in your browser.

Expected output

Delhi 28 Asha
Delhi 28 Dev
Pune 31 Ravi
Pune 25 Meera
youngest: Meera, oldest: Ravi