Basic lambda expression

Basic Syntax

The syntax of a lambda expression in Java is as follows:

(parameters) -> expression

// or

(parameters) -> { statements; }

Here, parameters are the input parameters to the lambda expression, -> is the lambda arrow operator, and expression or { statements; } is the body of the lambda expression.

Key Features of Lambda Expressions

  1. Optional Type Declaration: No need to declare the type of parameters as the compiler can infer the type from the context.
  2. Optional Parenthesis: No need to use parenthesis if there is only one parameter.
  3. Optional Curly Braces: No need to use curly braces if the body contains a single statement.
  4. Optional Return Keyword: The return keyword is not required if the body contains a single expression that returns a value.

Code Example

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

List<Integer> evenNumbers = numbers.stream()
                                   .filter(n -> n % 2 == 0)
                                   .collect(Collectors.toList());

In this example, the lambda expression n -> n % 2 == 0 is used as the predicate to filter out the odd numbers from the list.

Lambdas make it easier to write code in a more functional and concise style, especially when working with collections, streams, and functional interfaces. They promote the use of higher-order functions and enable more expressive and readable code.