Functional Interfaces And Lambda Expressions

functional interface is an interface that contains only one abstract method. You can create functional interface using @FunctionalInterface annotation. It mainly used to prevent you by giving compile time error if you include more than one abstract method accidentally. It is not required to annotate an interface using @FunctionalInterface if it has only one abstract method.

Functional Interfaces And Lambda Expressions

package com.startwithjava.oops;
@FunctionalInterface
public interface Printable {
  public void print();
}

Lambda Expression

A lambda expression is implementation of functional interface that is being implemented or instantiated anonymously. A lambda expression represents an anonymous function.

lambda expression has following three elements.

  1. A set of parameters
  2. A lambda operator (->)
  3. Function body

Java 8 introduces lambda expression which is great feature. Before lambda expression we have to use anonymous class to implement an interface and to provide implementation of methods to be used. In this approach we need to write more codes to invoke a method.

Why to use Lambda Expression?

  • No boilerplate code needed. Only focus on functionality of your method.
  • No need to specify type of parameters.
  • Concise code. Light-weight way to implement an functional interface.
  • Only one abstract method to be implement.

Has Lambda Expression been the replacement of Anonymous Class?

No. Because in Anonymous class you can implement more than one abstract methods and also can define instance variables,extra methods and anonymous intializer. But Lambda Expression does not allow more than one method implementation.

Key Points about Lambda Expression

 Parameters

  • A lambda expression can receive zero to n number of parameters
  • The type of the parameters can be explicitly declared or it can be inferred from the context.
  • Parameters are should be within parentheses and separated by commas. Parameter type is optional.
  • Empty parentheses are used to represent zero parameters.
  • When there is a single parameter then it is not mandatory to use parentheses.

 Function Body

  • Return type of lambda expression must be compatible with functional interface’s method.
  • The number of parameters of lambda expression must be same as functional interface’s method.
  • The function body curly braces are not required for single statement. But curly braces must be used to multiple statements.
  • If functional interface has method which returns some value then with single statement, return statement is optional. But must be used return statement with multiple statements.
  • Each exception thrown by the lambda body must be compatible with functional interface’s method.

Lambda Expression without Argument

 //No-arguments,empty parentheses and single statement
 @FunctionalInterface
 interface Printable{
   public void print();
 }
public class LambdaEx{
 public static void main(String args[]){ 
 Printable p = ()->System.out.println("Hello"); 
 p.print();
} 
}

Output


Hello

Lambda Expression with one argument

 //With argument and without parameter type 
 @FunctionalInterface
 interface Printable{
   public void display(String name);
 }
public class LambdaEx{

 public static void main(String args[]){

 Printable p = (n)->System.out.println(n);

 p.display("Hello");

}
}

Output


Hello

Lambda Expression with arguments and return value

With return type of method but no need to return through lambda expression because only one statement is there.

package com.startwithjava.oops;
interface InterfaceA {
public int sum(Integer n1,Integer n2);
}
public class LambdaEx {
 public static void main(String[] args) {
 InterfaceA a = (Integer n1,Integer n2)-> n1+n2;
 System.out.println(a.sum(10,10)); 
 System.out.println(a.sum(10,20));
}
}

Output

20
30

Complete Lambda Expression Example

MathOperation

package com.startwithjava.oops;

@FunctionalInterface
public interface MathOperation {
 public void operation(int x,int y,String operator);
}

 

LambdaExpressionEx
package com.startwithjava.oops;

public class LambdaExpressionEx {
	public static void main(String[] args) {			
	//lambda expression to implement operation method
	MathOperation p = (a,b,op)->{
	switch(op) {
		    case "+":
				 System.out.println("Sum = "+(a+b));
		     break;
			 case "-":
				 System.out.println("Subtraction = "+(a-b));
		     break;
		     
			 case "*":
				 System.out.println("Multiplication = "+(a*b));
		     break;
			 case "/":
				 System.out.println("Division= "+(a/b));
		     break;
			 case "%":
				 System.out.println("Modulo(%) = "+(a%b));
		     break;
			}
		 };
		
	p.operation(5,3,"+");
	p.operation(5,3,"-");
	p.operation(5,3,"*");
	p.operation(6,3,"/");
	p.operation(7,3,"%");
    System.out.println("By Using anonymous class");
   //Using anonymous class
    MathOperation p2 = new MathOperation(){ 
       public void operation(int a,int b,String s) {
        switch(s) { 
          case "+": System.out.println("Sum = "+(a+b)); 
          break; 
          case "-": System.out.println("Subtraction = "+(a-b)); 
          break; 
          case "*": System.out.println("Multiplication = "+(a*b)); 
          break;
          case "/": System.out.println("Division= "+(a/b)); 
          break; 
          case "%": System.out.println("Modulo(%) = "+(a%b)); 
          break; 
         }
        }
      };
    p2.operation(5,3,"+"); 
    p2.operation(5,3,"-"); 
    p2.operation(5,3,"*"); 
    p2.operation(6,3,"/"); 
    p2.operation(7,3,"%");
  }

}

Output

Sum = 8
Subtraction = 2
Multiplication = 15
Division= 2
Modulo(%) = 1
By Using anonymous class
Sum = 8
Subtraction = 2
Multiplication = 15
Division= 2
Modulo(%) = 1

Leave a Reply