What are the rules for the body of lambda expression in Java?

Java 8Object Oriented ProgrammingProgramming

A lambda expression is an anonymous function (nameless function) that has passed as an argument to another function. We need to follow some rules while using the body of a lambda expression.

Rules for the body of a lambda expression

  • The body of the lambda expression can be either a single expression or more statements.
  • If we are using a single expression as the body of a lambda expression, then no need to enclose the body with curly braces ({}).
  • If we are using one or more statements as the body of a lambda expression, then enclosing them within curly braces({}) can be mandatory.

Syntax

(parameters) OR () -> {body with statements separated by;} OR Single Statement

Example

interface Message {
   String message(String name);
}
public class LambdaExpressionBodyTest {
   public static void main(String args[]) {
      // Lambda expression using single expressio
      Message msg1 = msg -> "TutorialsPoint " + msg;
      System.out.println(msg1.message("Lambda Expression With Expression"));

      // Lambda expression using statement
      Message msg2 = msg -> { return "TutorialsPoint " + msg; };
      System.out.println(msg2.message("Lambda Expression With Statement"));

      // Lambda expression using multiple statements
      Message msg3 = msg -> {
         String hello = "TutorialsPoint " + msg;
         return hello;
      };
      System.out.println(msg3.message("Lambda Expression With Multiple Statement"));
   }
}

Output

TutorialsPoint Lambda Expression With Expression
TutorialsPoint Lambda Expression With Statement
TutorialsPoint Lambda Expression With Multiple Statement
raja
Published on 27-Dec-2019 12:12:15
Advertisements