Java Lambda Expressions
Lambda expressions, also known as closures, are the most important new feature that drove the release of Java 8.
Lambda allows a function to be passed as a parameter to a method (functions are passed into methods as arguments).
Using Lambda expressions can make code more concise and compact.
Syntax
The syntax format of a lambda expression is as follows:
parametersis the parameter list,expressionor{ statements; }is the body of the Lambda expression. If there is only one parameter, the parentheses can be omitted; if there are no parameters, empty parentheses are still required.
Below is a simple example showing the use of a Lambda expression to calculate the sum of two numbers:
Example
MathOperation addition = (a, b) -> a + b;
// Invoking the Lambda expression
int result = addition.operation(5, 3);
System.out.println("5 + 3 = " + result);
In the above example, MathOperation is a functional interface that contains an abstract method operation. The Lambda expression(a, b) -> a + bimplements this abstract method, representing the operation of adding the two parameters.
Lambda expressions can be used in various scenarios, including collection operations, event handling, etc. Below is an example of using a Lambda expression to iterate over a list:
Example
// Using Lambda expression to iterate over a list
names.forEach(name -> System.out.println(name));
Lambda expressions introduce a more functional programming style in Java, making code more concise and readable. They are an important improvement to functional programming in Java 8.
Important Features
Conciseness
Lambda expressions provide a more concise syntax, especially suitable for functional interfaces. Compared with traditional anonymous inner classes, Lambda expressions make code more compact and reduce boilerplate code.
Example
Runnable runnable1 = new Runnable() {
@Override
public void run() {
System.out.println("Hello World!");
}
};
// Using Lambda expression
Runnable runnable2 = () -> System.out.println("Hello World!");
Functional Programming Support
Lambda expressions are a manifestation of functional programming. They allow functions to be passed as arguments to methods or returned as return values. This support makes Java more flexible in functional programming, enabling better handling of tasks such as collection operations and parallel computing.
Example
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(name -> System.out.println(name));
Variable Capture
Lambda expressions can access variables in the outer scope. This feature is called variable capture. Lambda expressions can implicitly capture local variables that are final or effectively final.
Example
int x = 10;
MyFunction myFunction = y -> System.out.println(x + y);
myFunction.doSomething(5); // Output 15
Method References
Lambda expressions can be further simplified through method references. Method references allow you to directly reference methods of existing classes or objects without writing redundant code.
Example
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(System.out::println);
Parallelism
Lambda expressions make it more convenient to implement parallel operations. By using the Stream API combined with Lambda expressions, parallel computing can be implemented more easily, improving program performance.
Example
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.parallelStream().mapToInt(Integer::intValue).sum();
The introduction of Lambda expressions makes Java programming more flexible and concise, and promotes the development of functional programming.
Lambda Expression Examples
Simple examples of Lambda expressions:
// 1. 不需要参数,返回值为 5 () -> 5 // 2. 接收一个参数(数字类型),返回其2倍的值 x -> 2 * x // 3. 接受2个参数(数字),并返回他们的差值 (x, y) -> x – y // 4. 接收2个int型整数,返回他们的和 (int x, int y) -> x + y // 5. 接受一个 string 对象,并在控制台打印,不返回任何值(看起来像是返回void) (String s) -> System.out.print(s)
Enter the following code in the Java8Tester.java file:
Java8Tester.java File
Execute the above script and the output is:
$ javac Java8Tester.java $ java Java8Tester 10 + 5 = 15 10 - 5 = 5 10 x 5 = 50 10 / 5 = 2 Hello Example Hello Google
The following two points should be noted when using Lambda expressions:
-
Lambda expressions are mainly used to define method-type interfaces for inline execution (for example, a simple method interface). In the above example, we used various types of Lambda expressions to define the methods of the MathOperation interface, and then we defined the execution of operation.
-
Lambda expressions eliminate the hassle of using anonymous methods and give Java simple yet powerful functional programming capabilities.
Variable Scope
lambda expressions can only reference outer local variables marked as final. That is to say, local variables defined outside the lambda's scope cannot be modified inside the lambda; otherwise, a compilation error will occur.
Enter the following code in the Java8Tester.java file:
Java8Tester.java File
Execute the above script and the output is:
$ javac Java8Tester.java $ java Java8Tester Hello! Example
We can also directly access outer local variables in the lambda expression:
Java8Tester.java File
Local variables in lambda expressions do not need to be declared as final, but they must not be modified by subsequent code (that is, they implicitly have final semantics).
int num = 1; Converter<Integer, String> s = (param) -> System.out.println(String.valueOf(param + num)); s.convert(2); num = 5; //报错信息:Local variable num defined in an enclosing scope must be final or effectively final
It is not allowed to declare a parameter or local variable with the same name as a local variable inside a Lambda expression.
String first = ""; Comparator<String> comparator = (first, second) -> Integer.compare(first.length(), second.length()); //编译会出错
Other Extensions
Java 8 New Features