Comparator for Non-Comparable Types
What you'll learn: How to use Comparators to sort classes that don't implement Comparable or when you can't modify the class source code.
The Problem: Sorting Without Comparable
Not every class implements Comparable, and sometimes you don't control the source code to add it. Perhaps you're working with a third-party library, a legacy class, or simply a type where natural ordering doesn't make sense. That's where Comparator becomes essential—it lets you define sorting logic externally.
External Sorting Logic
Think of Comparator as a judging panel you bring to a competition. Even if the contestants (objects) don't have built-in ranking rules, the judges can still decide who wins based on whatever criteria they choose.
When a class doesn't implement Comparable, you simply create a Comparator to define the ordering:
class Book {
String title;
int pages;
Book(String title, int pages) {
this.title = title;
this.pages = pages;
}
}
// Book doesn't implement Comparable, but we can still sort it!
Comparator<Book> byPages = (b1, b2) -> Integer.compare(b1.pages, b2.pages);
Comparator<Book> byTitle = (b1, b2) -> b1.title.compareTo(b2.title);
List<Book> books = new ArrayList<>();
books.add(new Book("Java Basics", 300));
books.add(new Book("Advanced Java", 450));
Collections.sort(books, byPages); // Sort by page count
Collections.sort(books, byTitle); // Sort by title
When You'd Use This
- Sorting third-party classes you can't modify
- Defining multiple sort orders for the same type
- Separating sorting logic from the data class
- Working with classes where natural ordering is ambiguous
Key Takeaway: Comparators let you sort any type—even those that don't implement Comparable—by providing sorting logic externally, giving you complete flexibility without modifying the original class.