22_Lambda
文章目录
Lambda01–基本使用
Lambda 表达式是 Java 8 开始才有的语法
- 函数式接口(Functional Interface):只包含 1 个抽象方法的接口
可以在接口上面加上@FunctionalInterface
注解,表示它是一个函数式接口 - 当匿名类实现的是函数式接口时,可以使用 Lambda 表达式进行简化
@FunctionalInterface
public interface Testable {
void test(int v);
}
- 参数列表可以省略参数类型
- 当只有一条语句时,可以省略大括号、分号、
return
- 当只有一个参数时:可以省略小括号
- 当没有参数时:不能省略小括号
public interface Caculator {
int caculate(int v1, int v2);
}
static void execute(int v1, int v2, Caculator c) {
System.out.println(c.caculate(v1, v2));
}
public static void main(String[] args) {
execute(10, 20, (int v1, int v2) -> {
return v1 + v2; // 20
});
execute(11, 22, (v1, v2) -> v1 + v2); // 20
}
Lambda02–使用注意
- Lambda 只能访问
final
或者 有效 final 的局部变量 - Lambda 没有引入新的作用域
public class OuterClass {
@FunctionalInterface
public interface Testable {
void test(int v);
}
private int age = 1;
public class InnerClass {
private int age = 2;
void inner() {
// int v = 4; // error, Lambda 没有引入新的作用域, 重复定义变量
Testable t1 = v -> {
System.out.println(v); // 3
System.out.println(age); // 2
System.out.println(this.age); // 2
System.out.println(InnerClass.this.age); // 2
System.out.println(OuterClass.this.age); // 1
};
t1.test(3);
Testable t2 = new Testable() {
@Override
public void test(int v) {
System.out.println(v); // 3
System.out.println(age); // 2
// System.out.println(this.age); // error
System.out.println(InnerClass.this.age); // 2
System.out.println(OuterClass.this.age); // 1
}
};
t2.test(3);
}
}
public static void main(String[] args) {
new OuterClass().new InnerClass().inner();
}
}