Site icon

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 ?

3. Example of functional interface (Comparator) in java

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

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));
    }
}
Exit mobile version