1、Lambda表达式简介
Lambda表达式,也称为闭包,它是 Java 8 的新特性,
Lambda允许把函数作为一个方法的参数(函数作为参数传递进方法中),
使用 Lambda表达式可以使代码变的更加简洁紧凑,Lambda表达式的使用场景:用以简化接口实现。
public class LambaExpression {
public static MathOperation test = (int n1, int n2) -> {
return n1 * n2;
};
public static MathOperation test1 = (int n1, int n2) -> n1 - n2;
public static getMessage test2 = (String str) -> str;
public static void main(String[] args) {
System.out.println(test.operate(2, 3));
System.out.println(test1.operate(10,2));
System.out.println(test2.message("Hello,world"));
Sigle sigle = ()-> {
System.out.println("哈哈,Are you kiding me?");
};
sigle.fa();
}
interface MathOperation{
int operate(int n1, int n2);
}
@FunctionalInterface//定义必须是⼀个函数式接口
private interface getMessage{
String message(String s);
}
private interface Sigle{
void fa();
}
}
上面代码运行结果:
6
8
Hello,world
哈哈,Are you kiding me?
2、表达式对接口的要求:
虽然lambda表达式可以简化接口的实现。但是,并不是所有的接口都可以使用lambda表达式来简洁实现的。
Lambda表达式毕竟只是⼀个匿名方法。只能实现接口中的一个方法,也就是说接口类中有多个方法时是不适用的,编译器会直接报错。
Lambda表达式,只能实现函数式接口。
interface test{
int dog(int n);
int cat(int n);
}
上面的接口无法使用Lambda表达式。