Home >Java >javaTutorial >Lambda expression syntax

Lambda expression syntax

WBOY
WBOYOriginal
2024-02-19 20:56:29988browse

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:

  1. Lambda expression without parameters:

() -> "Hello, lambda!"

This Lambda expression has no parameters and returns a string "Hello, lambda!".

  1. Lambda expression with a single parameter:

x -> x * x

This Lambda expression has a parameter x and returns the square of x .

  1. Lambda expression with multiple parameters:

(x, y) -> x y

This Lambda expression has two parameters x and y, returns the sum of x and y.

  1. Lambda expression as an implementation of functional interface:

List numbers = Arrays.asList(1, 2, 3, 4, 5);
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 = Arrays.asList("Alice", "Bob", "Charlie");
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn