Simply put, a Java functional interface is an interface with a single abstract method. Functional interfaces were released with Java 8 and provide target types for lambda expressions. The java.util.function package contains various general purpose functional interfaces such as Predicate, Consumer, Function, and Supplier. For an an intro to Java lambda expressions click here: What are Lambdas in Java?.

The @FunctionalInterface annotation is also available, and will cause compile time errors when the associated interface is not actually a functional interface.

Functional Interface Examples

Here is is an example of creating a simple functional interface with the method doSomething(), and then creating an instance of that interface as a target type for a lambda expression:

//the functional interface
@FunctionalInterface
public interface FunctionalInterfaceExample {
   boolean doSomething(String s);
}

....

//using functional interface as target type (tests if string is empty)
FunctionalInterfaceExample funcInterfaceExample = t -> t.isEmpty();

Predicate is a functional interface found in java.util.function with the abstract method test(T t) returning a boolean. Here is an example of creating an instance of this functional interface as a target type of a lambda expression:

//using functional interface as target type (tests if first character in string is 'a');
Predicate<String> pred = t -> t.startsWith("a");

In order to successfully create an instance of a functional interface with a lambda expression, the interface and the lambda expression must have the same input parameter and return types.

Leave a Reply

What is a Java Functional Interface?