Comparator as a Functional Interface
You'll learn why Comparator is a functional interface and how lambda expressions make comparison code much cleaner.
What Makes Comparator Functional?
A functional interface is an interface with exactly one abstract method. Comparator<T> fits perfectly—it has a single abstract method: compare(T o1, T o2). This seemingly simple fact unlocks powerful syntax through lambda expressions.
Before functional interfaces were emphasized in Java 8, you wrote anonymous classes to create comparators (as you saw in the previous lesson). That approach worked but was verbose. Since Comparator has only one method to implement, Java can infer everything else when you use a lambda expression.
Lambda Syntax for Comparators
Think of a lambda as a shortcut: instead of writing out the entire anonymous class structure, you just write the parameters and the logic. The general pattern is:
(parameters) -> expression
For Comparator, the lambda receives two parameters (the objects to compare) and returns an integer:
Comparator<String> lengthComparator = (s1, s2) -> s1.length() - s2.length();
This single line replaces the entire anonymous class! Java knows you're implementing compare because Comparator has only that one abstract method.
Using Lambda Comparators
List<String> words = new ArrayList<>(Arrays.asList("apple", "kiwi", "banana"));
Collections.sort(words, (s1, s2) -> s1.length() - s2.length());
// words is now: [kiwi, apple, banana]
The lambda (s1, s2) -> s1.length() - s2.length() is automatically treated as a Comparator<String>.
Key Takeaway: Comparator is a functional interface with one abstract method (compare), allowing you to replace verbose anonymous classes with concise lambda expressions for cleaner, more readable sorting logic.