What is a lambda expression?

In mathematics and computing generally, a lambda expression is a function: for some or all combinations of input values it specifies an output value. Lambda expressions in Java introduce the idea of functions into the language. In conventional Java terms lambdas can be understood as a kind of anonymous method with a more compact syntax that also allows the omission of modifiers, return type, and in some cases parameter types as well.

Syntax

The basic syntax of a lambda is either

    (parameters) -> expression

or

    (parameters) -> { statements; }

Examples


1. (int x, int y) -> x + y                          // takes two integers and returns their sum
2. (x, y) -> x - y                                  // takes two numbers and returns their difference
3. () -> 42                                         // takes no values and returns 42 
4. (String s) -> System.out.println(s)              // takes a string, prints its value to the console, and returns nothing 
5. x -> 2 * x                                       // takes a number and returns the result of doubling it
6. c -> { int s = c.size(); c.clear(); return s; }  // takes a collection, clears it, and returns its previous size

Syntax notes

  • Parameter types may be explicitly declared (ex. 1,4) or implicitly inferred (ex. 2,5,6). Declared- and inferred-type parameters may not be mixed in a single lambda expression.
  • The body may be a block (surrounded by braces, ex. 6) or an expression (ex. 1-5). A block body can return a value (value-compatible, ex. 6) or nothing (void-compatible). The rules for using or omitting the return keyword in a block body are the same as those for an ordinary method body.
  • If the body is an expression, it may return a value (ex. 1,2,3,5) or nothing (ex. 4).
  • Parentheses may be omitted for a single inferred-type parameter (ex. 5,6)
  • The comment to example 6 should be taken to mean that the lambda could act on a collection. Equally, depending on the context in which it appears, it could be intended to act on an object of some other type having methods size and clear, with appropriate parameters and return types.

More precisely, it could take a collection; equally, it could
take some other compatible type. See the last syntax note.