什么是Lambad表达式
Lambda表达式其实就是一个匿名函数,直接对应于其中的Lambda抽象。Lambda表达式也可以称为闭包,它允许把函数作为一个方法的参数传递于方法中,可以更加简洁紧凑地展现代码。
Lambda表达式的基本语法如下:
(parameters) -> expression
(parameters) -> {statements;}
Lambda表达式的使用示例:
Arrays.asList(12,6,10,23).forEach((Integer x)-> System.out.println(x+2));
看下面的代码:
public class LambdaTest {
public static void main(String args[]){
LambdaTest lambda = new LambdaTest();
MathOperation addition = (int x, int y) -> x + y;
MathOperation subtraction = (int x, int y) -> x - y;
MathOperation multiplication = (int x, int y) -> x * y;
MathOperation division = (int x, int y) -> x / y;
System.out.println("8 + 4 = " + lambda.operate(8, 4, addition));
System.out.println("8 - 4 = " + lambda.operate(8, 4, subtraction));
System.out.println("8 x 4 = " + lambda.operate(8, 4, multiplication));
System.out.println("8 / 4 = " + lambda.operate(8, 4, division));
}
interface MathOperation {
int operation(int a, int b);
}
private int operate(int a, int b, MathOperation mathOperation){
return mathOperation.operation(a, b);
}
}
运行结果如下:
8 + 4 = 12
8 - 4 = 4
8 x 4 = 32
8 / 4 = 2