Lesson 7 of 10
Comparable & Comparator - Sorting Objects
Comparable<T> defines natural ordering (implemented by the class itself). Comparator<T> defines external, customisable ordering (separate from the class). Both are used by ArrayList.sort(), Collections.sort(), TreeSet, and PriorityQueue to order objects.
Comparable vs Comparator
import java.util.*;
public class Book implements Comparable<Book> {
private final String title;
private final String author;
private final double price;
private final int yearPublished;
public Book(String title, String author, double price, int year) {
this.title = title; this.author = author;
this.price = price; this.yearPublished = year;
}
// Natural ordering - books sorted by title alphabetically
@Override
public int compareTo(Book other) {
return this.title.compareToIgnoreCase(other.title);
}
// Getters
public String getTitle() { return title; }
public String getAuthor() { return author; }
public double getPrice() { return price; }
public int getYear() { return yearPublished; }
@Override
public String toString() { return title + " ($" + price + ")"; }
}
public class ComparatorDemo {
// Custom Comparators (reusable, named)
static final Comparator<Book> BY_PRICE =
Comparator.comparingDouble(Book::getPrice);
static final Comparator<Book> BY_PRICE_DESC =
Comparator.comparingDouble(Book::getPrice).reversed();
static final Comparator<Book> BY_YEAR_THEN_TITLE =
Comparator.comparingInt(Book::getYear)
.thenComparing(Book::getTitle); // chain comparators
static final Comparator<Book> BY_AUTHOR_THEN_PRICE =
Comparator.comparing(Book::getAuthor)
.thenComparingDouble(Book::getPrice);
public static void main(String[] args) {
List<Book> books = new ArrayList<>(List.of(
new Book("Effective Java", "Joshua Bloch", 44.99, 2018),
new Book("Clean Code", "Robert Martin", 39.99, 2008),
new Book("DDIA", "Martin Kleppmann", 49.99, 2017),
new Book("Atomic Habits", "James Clear", 24.99, 2018)
));
// Natural order (Comparable - by title)
Collections.sort(books);
System.out.println("By title: " + books);
// By price ascending
books.sort(BY_PRICE);
System.out.println("By price: " + books);
// By year, then title
books.sort(BY_YEAR_THEN_TITLE);
System.out.println("By year→title: " + books);
// Null-safe comparator
Comparator<String> nullSafe = Comparator.nullsFirst(Comparator.naturalOrder());
// TreeSet with custom comparator
TreeSet<Book> byPrice = new TreeSet<>(BY_PRICE);
byPrice.addAll(books); // automatically sorted by price
System.out.println("TreeSet first (cheapest): " + byPrice.first());
}
}Quick Quiz
Tip
Tip
Practice Comparable Comparator Sorting Objects in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Comparable & Comparator - Sorting Objects
Practice Task
Note
Practice Task - (1) Write a working example of Comparable Comparator Sorting Objects from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Comparable Comparator Sorting Objects is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.
Finished this lesson?