Java Tutorials

Java Functional Interfaces

    Java 8 introduced Lambda Expressions, These expressions depends on Functional Interfaces. A Functional Interface is an Interface which has only one Abstract method, and also it can have static and default methods. It can optionally be decorated with @FunctionalInterface Annotation.

Earlier java(i.e before JDK8) , an interfaces can be implemented using class/anonymous class. An anonymous class is a class which has no class name, and can implement interface methods.

Functional interfaces can be used as a return type for lambda expressions and method references.

for ex: implementing interface as an Anonymous class.

Interface implementing using Anonymous Class

interface IA
int add ( int a, int b );
public class TestImpl  {

IA  obj =  new IA(){
int  add ( int a, int a )
	return a + b;
public static void main(String[] args)
Interface implementation using Anonymous Class");

TestImpl  impl = new TestImpl ();
int result = impl.obj.add( 10 , 20 );
System.out.println("Calling interface 
add method :  "+ result);        		

Interface implementation using Lambda Expression

        	//creating Anonymous method, assiging it to functional interface IA
        	IA   anyonymous  = ( a ,  b ) -> a + b;
        	//Invoking  Anonymous method 
        	int result = anonymous.add( 10, 20 );
		System.out.println("Calling interface add method using Lambda Expression :  "+ result);        		

Java 8 provides many built-in Functional Interfaces. These interfaces located in java.util.function package

BiConsumer             BiFunction             BiPredicate            BinaryOperator         
BooleanSupplier        Consumer               DoubleBinaryOperator   DoubleConsumer         
DoubleFunction         DoublePredicate        DoubleSupplier         DoubleToIntFunction    
DoubleToLongFunction   DoubleUnaryOperator    Function               IntBinaryOperator      
IntConsumer            IntFunction            IntPredicate           IntSupplier            
IntToDoubleFunction    IntToLongFunction      IntUnaryOperator       LongBinaryOperator     
LongConsumer           LongFunction           LongPredicate          LongSupplier           
LongToDoubleFunction   LongToIntFunction      LongUnaryOperator      ObjDoubleConsumer      
ObjIntConsumer         ObjLongConsumer        Predicate              Supplier               
ToDoubleBiFunction     ToDoubleFunction       ToIntBiFunction        ToIntFunction          
ToLongBiFunction       ToLongFunction         UnaryOperator 		
Java built-in functional interfaces are categorized into 5 parts