Functional Interface in Java 8

An Interface with only one single abstract method is a functional interface. In addition, We can add a @FunctionalInterface annotation to allows the compiler to generate an error at compile time if Interface does not match the required conditions.

However, if the annotation is not added and Interface has only one abstract method and multiple default methods still it will be a Functional Interface, the only difference is compiler will not check the prerequisites for a Functional Interface. 

In Java 8 lambda expression can be used to represent the instance of Functional Interface. There are many Interface available in JDK, like  Runnable, Comparable, Callable, PrivilegedAction,ActionListener are some examples of functional interface.

java.util.function package also contains functional interfaces like Predicate, BinaryOperator, and Function.

Predicate: Predicate interface has a single abstract method named test, which returns a boolean value.

@FunctionalInterface
public interface Predicate {

    boolean test(T t);

}

BinaryOperator: BinaryOperator interface extends BiFunction Interface having an abstract method apply which takes two parameters of the same type and returns the same type result.

@FunctionalInterface
public interface BinaryOperator{

 T apply(T t, T t);

}

Function: Function Interface represents a method that accepts one argument of type T and produces a result of type R.

@FunctionalInterface
public interface Function<T, R> {

    R apply(T t);

}

Let's demonstrate an example of a functional Interface.

@FunctionalInterface
interface Operation 
{ 
	boolean isEven(int x); 
} 

class FunctionalTest 
{ 
	public static void main(String args[]) 
	{ 
		int a = 6; 

		/**lambda expression to define the isEven method */ 
		Operation o = (int x)->x%2==0; 

		/**argument passed and return type must be same*/
		boolean isEven = o.isEven(a); 
		System.out.println(isEven); 
	} 
} 
Output : true