Home >Java >javaTutorial >Lambda expression syntax
Lambda expression is a commonly used expression form in functional programming. It provides a concise and flexible programming method. In Java 8 and later versions, Lambda expressions have become an important programming tool and are widely used in the implementation of functional interfaces.
The basic format of Lambda expression is as follows:
(parameter) -> expression
Among them, parameter represents the parameter list of Lambda expression, which can contain one or more Parameter; expression is the body of the Lambda expression, which can be an expression or a series of statements. Lambda expressions can have a return value, which can also be void.
Here are some specific code examples:
() -> "Hello, lambda!"
This Lambda expression has no parameters and returns a string "Hello, lambda!".
x -> x * x
This Lambda expression has a parameter x and returns the square of x .
(x, y) -> x y
This Lambda expression has two parameters x and y, returns the sum of x and y.
List
numbers.forEach((Integer num) -> System.out.println(num));
In this example, Lambda expression is used as the implementation of the forEach method, outputting each item in the list elements.
Lambda expressions can also use method references to further simplify the code. Method reference refers to directly calling an existing method as the body of a Lambda expression. For example:
List
names.forEach(System.out::println);
In this example, the method reference System.out::println is used, and the System.out.println method is directly called to output each element in the list.
The format of Lambda expression is concise and flexible, allowing us to implement the methods or functions of the interface in a more streamlined way. By using Lambda expressions and method references, we can write code more clearly and concisely, and improve the readability and maintainability of the code.
The above is the detailed content of Lambda expression syntax. For more information, please follow other related articles on the PHP Chinese website!