How can we use lambda expressions with functional interfaces in Java?


The lambda expressions are anonymous functions and don't have any return type, access modifier and not belonging to any class. It can be used to simplify the implementation of the abstract method in a functional interface. Whenever there is a functional interface, we can use lambda expressions instead of anonymous inner classes.

Syntax

([comma seperated argument-list]) -> {body}

Example

@FunctionalInterface
interface BonusCalculator {
   public double calcBonus(int amount);
}
class EmpDetails {
   public void getBonus(BonusCalculator calculator, int amount) {
      double bonus = calculator.calcBonus(amount);
      System.out.println("Bonus: " + bonus);
   }
}
public class LambdaExpressionTest {
   public static void main(String[] args) {
      EmpDetails details = new EmpDetails();
      //Using Anonymous inner class
      EmpDetails details = new EmpDetails();
      details.getBonus(new BonusCalculator () {
         public double calcBonus(int amount) {
            System.out.println("Bonus Calculation of an Employee using Ananymous inner class");
            return amount*2;
         }
      },2000);
      // using Lambda Expression
      details.getBonus((amount) -> {
         System.out.println("Bonus Calculation of an Employee using Lambda Expression");
         return amount*2;
      },2000);
   }
}

Output

Bonus Calculation of an Employee using Anonymous inner class
Bonus: 4000.0
Bonus Calculation of an Employee using Lambda Expression
Bonus: 4000.0
raja
Published on 04-Dec-2019 07:28:06
Advertisements