Lesson 5 of 616 minModule progress 0%

Module 11: Collections Framework in Practice

Sorting with Comparable and Comparator

Sort objects cleanly using Comparable and Comparator.

Author

Java Learner Editorial Team

Reviewer

Technical review by Java Learner

Last reviewed

2026-04-17

Java version

Java 25 LTS

How this lesson was prepared: AI-assisted draft, manually edited for clarity, and checked against current Java documentation and runnable examples.

Learning goals

  • Know when to use `Comparable`
  • Use `Comparator` for alternate sort orders
  • Write readable comparator logic

Comparable defines a default natural order inside the class: This is useful when there is one obvious main sort order.

Comparator is for alternate or external sort rules: It is better when different screens or reports need different orders.

Comparator helpers keep code shorter: Method references and Comparator.comparing(...) often read better than manual compare chains.

Intermediate design rule: Do not cram every possible ordering decision into the domain class itself.

Runnable examples

Sort by name length with a comparator

var names = new java.util.ArrayList<>(java.util.List.of("Ada", "Grace", "Linus"));
names.sort(java.util.Comparator.comparingInt(String::length));
System.out.println(names);

Expected output

[Ada, Grace, Linus]

Mini exercise

Sort a list of products by price using `Comparator.comparingDouble(...)`.

Summary

  • `Comparable` gives one natural order.
  • `Comparator` gives flexible alternate orderings.
  • External sort rules usually belong in comparators, not inside the domain class.

Next step

Wrap the collections module with a contact management mini-project.

Sources used

Advertisement

Lesson check

When is `Comparator` especially useful?

Next lesson →