What is the usage of lambda in Java?
In Java, lambda expressions are used to simplify the implementation of functional interfaces. Lambda expressions are anonymous functions with parameter lists, function bodies, and possibly return types. They can replace the use of anonymous inner classes to implement instances of functional interfaces.
The general syntax for lambda expressions is as follows:
(parameters) -> { function body }
The parameter list contains zero or more parameters, while the lambda body is the function body of a lambda expression, which can be an expression or a block of code.
Lambda expressions can be used for functional interfaces, which are interfaces that contain only one abstract method. Using lambda expressions can make it more concise to implement methods of the interface, and can directly pass lambda expressions as parameters at the place of method invocation.
For example, let’s say we have a functional interface called Calculator, which defines an abstract method calculate. We can implement this interface’s method using a lambda expression, as shown below:
interface Calculator {
int calculate(int a, int b);
}
public class Main {
public static void main(String[] args) {
// 使用lambda表达式实现calculate方法
Calculator add = (a, b) -> a + b;
Calculator subtract = (a, b) -> a - b;
// 调用calculate方法
System.out.println(add.calculate(5, 3)); // 输出:8
System.out.println(subtract.calculate(5, 3)); // 输出:2
}
}
In the example above, the calculate method of the Calculator interface is implemented using lambda expressions to perform addition and subtraction operations. Then, in the main method, the calculate method is called to perform the corresponding calculations and output the results.