Java 8 Functional interface explained with examples (Comparator)

1. What is functional interface in java8?

  1. The interface having one abstract method is called functional interface.
    • The interface can contains other default methods but needs to have one abstract method.
  2. The functional interface are generally marked with annotation “@FunctionalInterface”.
    • Which signifies that they are functional interface.
  3. Having said that, It is not mandatory to mark functional interface with annotation
    • i.e. We can have functional interface without annotation “@FunctionalInterface”.

2. What are the attributes of functional interface ?

  • Functional interface needs to have single abstract method.
    • Functional interface can have other methods, declared in Object class like equals, toString, hashcode etc.
  • Functional interface can have default methods (Java 8 feature)

3. Example of functional interface (Comparator) in java

We will look into the comparator interface which satisfy all the above points.

  • Comparator interface has abstract method compare
  • Comparator interface have equals method
    • equals method is Object class method.
  • Comparator interface has many defaults methods
    • We have listed few of them in below code

4. Application of functional interface in java

5. Program – functional interface Comparator in Java8 JDK

@FunctionalInterface
public interface Comparator {

    int compare(T o1, T o2);

    boolean equals(Object obj);

    default Comparator reversed() {
        return Collections.reverseOrder(this);
    }

    default Comparator thenComparing(Comparator<? super T> other) {
        Objects.requireNonNull(other);
        return (Comparator & Serializable) (c1, c2) -> {
            int res = compare(c1, c2);
            return (res != 0) ? res : other.compare(c1, c2);
        };
    }

    default  Comparator thenComparing(
            Function<? super T, ? extends U> keyExtractor,
            Comparator<? super U> keyComparator)
    {
        return thenComparing(comparing(keyExtractor, keyComparator));
    }

    default > Comparator thenComparing(
            Function<? super T, ? extends U> keyExtractor)
    {
        return thenComparing(comparing(keyExtractor));
    }
}
Scroll to Top