How can we write a multiline lambda expression in Java?


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

Updated on: 10-Jul-2020

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements