Java - Lambda Expressions Syntax shorthand

Introduction

The following sections discuss the shorthand syntax for declaring lambda expressions.

Omitting Parameter Types

You can omit the type of the parameters in Lambda Expressions.

The compiler will infer the types of parameters from the context.

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

The Types of parameters are declared in the above code and can be omitted

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

Single Parameter

You can omit the parentheses if you omit the parameter type in a single parameter lambda expression.

(String msg) -> { System.out.println(msg); }

The code above declares the parameter type and can be omitted the parameter type as

(msg) -> { System.out.println(msg); }

And further it can omit the parameter type and parentheses

msg -> { System.out.println(msg); }

No Parameters

If a lambda expression does not take any parameters, you need to use empty parentheses.

() -> { System.out.println("Hello"); }

It is not allowed to omit the parentheses. The following declaration will not compile:

-> { System.out.println("Hello"); }

Parameters with Modifiers

You can use modifiers, such as final, in the parameter declaration. The following two lambda expressions are valid:

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

The following code will not compile since it uses the final modifier without the parameter type:

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

Body of Lambda Expressions

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

A block statement is enclosed in braces; a single expression is not enclosed in braces.

A return statement or the end of the body returns the control to the caller of the lambda expression.

The following two lambda expressions are the same; one uses a block statement and the other an expression:

Uses a block statement. Takes two int parameters and returns their sum.

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

Uses an expression. Takes a two int parameters and returns their sum.

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

The following two lambda expressions are the same.

Uses a block statement

(String msg) -> { System.out.println(msg); }

Uses an expression

(String msg) -> System.out.println(msg)