What is the syntax for lambda expressions in Java?


A lambda expression is an anonymous method (method without a name) that can be used to provide the implementation of a method defined by the functional interface.

Syntax

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

Rules for Lambda Expression Syntax

  • We can omit the datatypes since the compiler able to guess the type of parameters. When there is a single argument the parentheses also omitted.
  • The arrow token (->) can be able to connect the argument and functionality. It is mandatory.
  • The body contains a list of statements and expressions. In the case of a single statement or expression, the curly braces have omitted.

Example

interface EvenOrOdd {
   void check(int a);
}
public class LambdaExpressionTest1 {
   public static void main(String[] args) {
      EvenOrOdd evenOrOdd = (int a) -> {      // Lambda Expression 
         if(a% 2== 0){
            System.out.println("The number "+ a +" is even");
         } else {
            System.out.println("The number "+ a +" is odd");
         }
      };
      evenOrOdd.check(7);
      evenOrOdd.check(10);
   }
}

Output

The number 7 is odd
The number 10 is even
raja
Published on 05-Dec-2019 07:15:01
Advertisements