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 befor 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.

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(){
        	
@override
int  add ( int a, int a )
{
	return a + b;
}
        	
};
        	
public static void main(String[] args)
{
System.out.println("
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 		
		

ADS