Implementing Comparator with Anonymous Classes
What you'll learn: How to create custom sorting logic on-the-fly using anonymous classes without needing separate named classes.
The Core Idea
While Comparable defines the natural ordering inside a class, Comparator lets you define external ordering logic without modifying the original class. An anonymous class is a one-time, unnamed implementation created right where you need it—perfect for creating custom Comparator instances inline.
Think of it like hiring a temporary judge for a specific contest. You don't need to give them an official title or office; they exist only for that one event and apply custom rules you define on the spot.
The Syntax Pattern
Instead of creating a separate named class implementing Comparator, you write the implementation directly as an argument:
List<String> words = new ArrayList<>();
words.add("apple");
words.add("pie");
words.add("banana");
// Anonymous class implementing Comparator
Collections.sort(words, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return Integer.compare(s1.length(), s2.length());
}
});
// Result: ["pie", "apple", "banana"] (sorted by length)
How It Works
The anonymous class syntax creates a nameless implementation of Comparator<String> right there. You override the compare method with your custom logic—in this case, comparing string lengths instead of alphabetical order.
You can use this anywhere a Comparator is expected: with Collections.sort(), Arrays.sort(), when constructing a TreeSet, or creating a TreeMap.
Example with Multiple Fields
List<String> names = Arrays.asList("Alice", "Bob", "Eve");
Collections.sort(names, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
// Sort by length first, then alphabetically
int lengthCompare = Integer.compare(s1.length(), s2.length());
if (lengthCompare != 0) {
return lengthCompare;
}
return s1.compareTo(s2);
}
});
Key Takeaway: Anonymous classes let you implement Comparator inline, defining custom sorting logic exactly where it's needed without creating separate named classes.