Command Palette

Search for a command to run...

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

nullsFirst, case-insensitive order and reversed

Natural String order is by character code, so the capital F in "Fig" sorts before every lowercase word.

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.

nullsFirst, case-insensitive order and reversed
Sign in to run this example in your browser.

Expected output

[null, null, Fig, apple, banana, pear]
[apple, banana, Fig, pear, null, null]
[banana, apple, pear, Fig]