What are lambda expressions and how to use them in Java?



Lambda expressions are introduced in Java 8. These are used primarily to define inline implementation of a functional interface, i.e., an interface with a single method only.

Lambda expression eliminates the need of anonymous class and gives a very simple yet powerful functional programming capability to Java.

Syntax

parameter -> expression body

Example

Live Demo

public class Java8Tester {
   public static void main(String args[]) {
      Java8Tester tester = new Java8Tester();
      //with type declaration
      MathOperation addition = (int a, int b) -> a + b;
      
      //without type declaration
      MathOperation subtraction = (a, b) -> a - b;
      
      //with return statement along with curly braces
      MathOperation multiplication = (int a, int b) -> { return a * b; };
      
      //without return statement and without curly braces
      MathOperation division = (int a, int b) -> a / b;
      System.out.println("10 + 5 = " + tester.operate(10, 5, addition));
      System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction));
      System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication));
      System.out.println("10 / 5 = " + tester.operate(10, 5, division));
      
      //without parenthesis
      GreetingService greetService1 = message ->
      System.out.println("Hello " + message);
      
      //with parenthesis
      GreetingService greetService2 = (message) ->
      System.out.println("Hello " + message);
      greetService1.sayMessage("Mahesh");
      greetService2.sayMessage("Suresh");
   }
   interface MathOperation {
      int operation(int a, int b);
   }
   interface GreetingService {
      void sayMessage(String message);
   }
   private int operate(int a, int b, MathOperation mathOperation) {
      return mathOperation.operation(a, b);
   }
}

Output

10 + 5 = 15
10 - 5 = 5
10 x 5 = 50
10 / 5 = 2
Hello Mahesh
Hello Suresh
Samual Sam
Samual Sam

Learning faster. Every day.


Advertisements