A functional interface is an interface with a single abstract method. The goal is to define the signature of a method that can be used to pass as a parameter :

  • A reference to a static method
  • A reference to an instance method
  • A reference to a manufacturer
  • A lambda expression.

A functional interface can be annotated with the @FunctionalInterface annotation. Although the @FunctionalInterface annotation is not required, it has an important role allowing the compiler to force the interface to contain only one abstract method. If we try to define more than one abstract method in an interface annotated with @FunctionalInterface, the compiler will display an error.

@FunctionalInterface
public interface SimpleFunctionalInterface{
     void play();
      default int sum(int x , int y)
         { return x+y;
                     }
}

JDK 8 provides several functional interfaces by default. Old API interfaces have been migrated such as “Comparable” and “Runnable“.

We list the most used interfaces below :

Function:

A “Function” interface takes one argument and returns a result whose functional method is “apply (Object)“.

Supplier:

The “Supplier” interface produces a result of a given type. Unlike the “Function” interface, “Supplier” does not accept arguments. The abstract method of this interface is “get ()“.

Consumer:

The “Consumer” interface represents an operation that accepts a single argument and returns no results. The abstract method of this interface is “accept (Object)

Predicate:

The “Predicate” interface represents an operation that accepts a single argument and returns a result of type “Boolean”. The abstract method of this interface is “test (Object)“.

Comparator:

The “Comparator” interface is well known in older versions of Java. It is a comparison function, which imposes a full order on certain collectibles via its abstract method “compare (T o1, T o2)“.

BiFunction:

Represents a function that takes two arguments and produces a result. This is the specialization of two arities of the “Function” interface. The abstract method of this interface is “apply (T t, U u)“.

Commentaires

  1. Pingback: Lambda Expressions in JAVA 8 (Simple Tutorial) » JavaTuto

  2. Pingback: Codingame Solution : recopieElementsApresJava8 » JavaTuto

Laisser un commentaire