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.
return
keyword is not required if the body contains a single expression that returns a value.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.