Course contentsShow
← Java
Lesson 647 of 2,87015. Nested and Inner ClassesFree lesson

Use Case: Comparators and Functional Interfaces

Create custom Comparator implementations and other functional interfaces using anonymous classes.

Use Case: Comparators and Functional Interfaces

What you'll learn: How to create custom sorting logic and functional interface implementations using anonymous classes.

The Core Idea

In Java, interfaces like Comparator define a single abstract method that describes a specific behavior. Before lambdas existed, anonymous classes were the primary way to quickly implement these interfaces inline, especially when you needed custom comparison logic for sorting collections. Instead of creating a separate named class file, you write the implementation right where you need it.

Creating a Custom Comparator

Suppose you have a list of strings you want to sort by length, not alphabetically. The Comparator interface requires you to implement a compare(T o1, T o2) method. Using an anonymous class:

List<String> words = new ArrayList<>();
words.add("apple");
words.add("pie");
words.add("banana");

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]

Here, new Comparator<String>() { ... } creates an anonymous class implementing the Comparator interface. You provide the comparison logic inline without needing a separate class file.

Why This Matters

Anonymous classes let you create one-off implementations for functional interfaces (interfaces with a single abstract method). This is perfect for sorting, filtering, or callback scenarios where creating a full named class feels like overkill.

Think of it like ordering a custom sandwich: you describe exactly what you want on the spot, rather than having a named menu item for every possible combination.

Key Takeaway:
Anonymous classes provide a concise way to implement functional interfaces like Comparator inline, enabling custom behavior without creating separate class files.