Java 8 introduced lambda expressions, which are compact blocks of code that take parameters and return values. Similar to methods, lambda expressions do not require a name and can be directly implemented within the body of a method.
The most basic lambda expression consists of a single parameter and an expression.
parameter |
When utilizing more than one parameter, enclose them within parentheses.
(parameter1, parameter2) |
Expressions are constrained; they must promptly return a value and cannot encompass variables, assignments, or statements like if or for. For more intricate operations, a code block enclosed in curly braces can be employed. If the lambda expression necessitates returning a value, the code block should feature a return statement.
(parameter1, parameter2) |
Lambda expressions are commonly supplied as arguments to functions.
Utilize a lambda expression within the forEach() method of the ArrayList to print each item in the list.
import public |
Lambda expressions can be assigned to variables if the variable’s type is an interface with only one method. The lambda expression must possess the same number of parameters and the same return type as that method. Java includes several built-in interfaces of this type, such as the Consumer interface (found in the java.util package), which is commonly used with lists.
Utilize Java’s Consumer interface to store a lambda expression within a variable.
import
|
For incorporating a lambda expression within a method, the method should accept a parameter with a single-method interface as its type. Invoking the method of this interface will execute the lambda expression.
Generate a method that accepts a lambda expression as an argument.
interface
|