Introduction
Java introduced functional interfaces in Java 8 to support lambda expressions and functional programming paradigms. While interfaces like Comparator are commonly used with lambdas, a common question arises:
Is the Comparable interface a functional interface?
Short Answer: No, Comparable is Not a Functional Interface
While the Comparable interface appears to fit the mold of a functional interface because it declares only one abstract method—compareTo(T o)—there's a key distinction that disqualifies it:
Why Comparable is Not a Functional Interface
- A functional interface must have exactly one abstract method.
- Even though
Comparable declares just one (compareTo), it inherits the equals(Object obj) method from Object. - According to the Java Language Specification, this inherited method counts toward the interface’s abstract methods.
Because of this, Comparable has two abstract methods:
compareTo(T o)equals(Object obj) (inherited)
Thus, it does not meet the criteria for a functional interface.
But What About Comparator?
The Comparator interface is a functional interface. It defines a single abstract method:
java
int compare(T o1, T o2);
This makes it eligible for use with lambda expressions, and it’s the preferred choice when writing inline sorting logic.
Example Using Comparator with Lambda:
java
List<String> names = Arrays.asList("Charlie", "Alice", "Bob");
Collections.sort(names, (a, b) -> a.compareToIgnoreCase(b));
Conclusion
Although Comparable seems like a functional interface at first glance, it is not, due to the inherited equals() method from Object.
If you're looking for a functional interface for sorting, use the Comparator interface, which works seamlessly with lambda expressions and modern Java programming techniques.