Java Lambda Expression Syntax¶
Lambda expressions in Java provide a way to represent functionality or methods as arguments, essentially allowing developers to pass actions or logic directly.^[600-developer-java-java8-java8-lambda.md] This concept allows Java to treat behavior as data, similar to callback functions in other languages^[600-developer-java-java8-java8-lambda.md].
A Lambda expression is typically used in the context of a Functional Interface^[600-developer-java-java8-java8-lambda.md].
Syntax and Arguments¶
The syntax for a Lambda expression generally follows the format (arguments) -> { body }^[600-developer-java-java8-java8-lambda.md].
A standard implementation involves passing the lambda as an argument to a method that expects a Functional Interface, such as java.util.Function^[600-developer-java-java8-java8-java8-lambda.md#L15-L30].
Examples¶
When working with the java.util.Function<Integer, Integer> interface, the arrow token (->) is used to separate the parameter from the logic applied to it^[600-developer-java-java8-java8-lambda.md#L15-L30].
- Multiplication:
param -> param * param - Addition:
param -> param + param - Division:
param -> param / param^[600-developer-java-java8-java8-lambda.md#L15-L30]
In these examples, param represents the input argument, and the operation following the arrow determines the return value^[600-developer-java-java8-java8-lambda.md#L15-L30].
Common Functional Interfaces¶
Lambda expressions are used to implement the abstract methods of specific functional interfaces found in the java.util.function package^[600-developer-java-java8-java8-lambda.md#L32-L38].
- Consumer: Represents a function that accepts a single argument and returns no result (
T -> void)^[600-developer-java-java8-java8-lambda.md#L32-L38]. - Function: Represents a function that accepts one argument and produces a result (
T -> R)^[600-developer-java-java8-java8-lambda.md#L32-L38]. - Predicate: Represents a function that accepts one argument and returns a boolean value (
T -> boolean)^[600-developer-java-java8-java8-lambda.md#L32-L38]. - Supplier: Represents a function that accepts no arguments and returns a result (nilary function to
R)^[600-developer-java-java8-java8-lambda.md#L32-L38].
Sources¶
600-developer-java-java8-java8-lambda.md