Syntax and Structure of Lambda Expressions

Lambda expressions provide a clear and concise way to represent a functional interface using an anonymous function. Introduced in Java 8, they are used primarily to implement methods of functional interfaces in a simplified syntax.

Basic Syntax

(parameters) -> expression

Or, if the body contains multiple statements:

(parameters) -> {
    // multiple statements
    return value;
}Code language: JavaScript (javascript)

Components of Lambda Expressions

  1. Parameters:
    The lambda can have zero or more parameters. If there is only one parameter and its type is inferred, parentheses can be omitted.

  2. Arrow Token (->):
    Separates the parameter list from the body of the lambda expression.

  3. Body:
    This contains either a single expression (no braces or return needed) or a block of code enclosed in curly braces (braces and return are required if a return value is expected).

Forms of Lambda Expressions

  1. No Parameters:

() -> System.out.println("Hello");Code language: CSS (css)

    2. One Parameter (Type Inferred):

s -> System.out.println(s);Code language: CSS (css)

       3. Multiple Parameters with Types:

(int a, int b) -> a + b;

      4. Block Body with Return:

(int x, int y) -> {
    int sum = x + y;
    return sum;
};Code language: JavaScript (javascript)

Type Inference

Java’s compiler can infer the types of parameters based on the context (usually the target functional interface). You can omit the types for a cleaner expression.

(a, b) -> a + b

This is valid when the lambda is being assigned to a functional interface like BiFunction<Integer, Integer, Integer>.

Use with Functional Interfaces

Lambda expressions can only be used where a functional interface is expected.

For example:

Runnable r = () -> System.out.println("Running");
//Here, Runnable is a functional interface with a single run() method.Code language: JavaScript (javascript)

Return Type

  • If the lambda has a single expression, it is automatically returned.

  • If the lambda has a block body, the return keyword must be used explicitly when returning a value.

Lambda expressions streamline the syntax for implementing functional interfaces by eliminating the need for boilerplate code like anonymous inner classes. Their concise, expressive syntax improves readability and makes Java more functional in nature.

Scroll to Top