Lambda Expressions Body

Description

The lambda expression body can be a block statement or a single expression.

A block statement is enclosed in braces while a single expression can exist without braces.

In the block statement we can use return statement to return value.

The following lambda expression uses a block statement and use return statement to return the sum.

(int x, int y) -> { return x + y; }

While the following lambda uses an expression:

(int x, int y) -> x + y

The expression doesn't require the braces.

The lambda is not necessary to return a value. The following two lambda expressions just output the parameter to standard output and don't return anything.


(String msg)->{System.out.println(msg);}// a  block   statement
(String msg)->System.out.println(msg)   //an expression

Example


public class Main {
  public static void main(String[] argv) {
    Processor stringProcessor = (String str) -> str.length();
    String name = "Java Lambda";
    int length = stringProcessor.getStringLength(name);
    System.out.println(length);//  w  w w.  j  a v  a  2  s . co m

  }
}

@FunctionalInterface
interface Processor {
  int getStringLength(String str);
}

The code above generates the following result.





















Home »
  Java Lambda »
    Java Lambda Tutorial »




Java Lambda Tutorial