How can we write a multiline lambda expression in Java?

Java 8Object Oriented ProgrammingProgramming

Lambda expression is an anonymous method that has used to provide an implementation of a method defined by a functional interface. In Java 8, it is also possible for the body of a lambda expression to be a complex expression or statement, which means a lambda expression consisting of more than one line. In that case, the semicolons are necessary. If the lambda expression returns a result then the return keyword is also required.

Syntax

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

Example

interface Employee {
   String displayName(String s);
}
public class MultilineLambdaTest {
   public static void main(String[] s) {
      Employee emp = (x) -> {     // Lambda Expression with multiple lines
         x = "Jai " + x;
         System.out.println(x);
         return x;
      };
      emp.displayName("Adithya");
   }
}

Output

Jai Adithya
raja
Published on 16-Dec-2019 12:38:51
Advertisements