Lambada 表达式用来简化匿名内部类的写法,
只要是函数式接口就可以用 Lambda 表达式简化
//函数式接口: 接口中有且只有⼀个未实现的⽅法,这个接口就叫函数式接口
//函数式接口用@FunctionalInterface 注解
无 lambada 表达式之前:
- 匿名内部类
- 实现类
以下是使用对比:
//函数式接口
interface MyInterface {
int sum(int i, int j);
}
//方法1:实现类
public class MyInterfaceImpl implements MyInterface {
@Override
public int sum(int i, int j) {
return i + j;
}
}
public class Test {
public static void main(String[] args) {
//方法1:
MyInterface myInterface = new MyInterfaceImpl();
//方法2:匿名内部类:
MyInterface myInterface = new MyInterface() {
@Override
public int sum(int i, int j) {
return i + j;
}
};
//方法3:Lambda 表达式
MyInterface myInterface = (i, j) -> i + j;
System.out.println(myInterface.sum(1, 2));
}
}

