1、什么是lambda表达式
Lambda 表达式,也可称为闭包,它是推动 Java 8 发布的最重要新特性。
Lambda 允许把函数作为一个方法的参数(函数作为参数传递进方法中)。
使用 Lambda 表达式可以使代码变的更加简洁紧凑。
2、实现lambda表达式前提
- 必须是一个函数式接口
所谓的函数式接口,实际上就是接口里面只能有一个抽象方法的接口。例如Runnable 接口
public interface Runnable {
public abstract void run();
}
3、lambda表达式的由来
演变过程:外部类–>静态内部类–>局部内部类–>匿名内部类–>lambda表达式
1、外部类
public class CallTest{
public static void main(String[] args) {
new My().myMethod();
}
}
// 函数式接口
interface MyBase{
public void myMethod();
}
// 外部类
class My implements MyBase{
@Override
public void myMethod() {
System.out.println("我结婚了");
}
}
2、静态内部类
public class CallTest{
// 静态内部类
static class My implements MyBase{
@Override
public void myMethod() {
System.out.println("我结婚了");
}
}
public static void main(String[] args) {
new My().myMethod();
}
}
// 函数式接口
interface MyBase{
public void myMethod();
}
3、局部内部类
public class CallTest{
public static void main(String[] args) {
// 局部内部类
class My implements MyBase{
@Override
public void myMethod() {
System.out.println("我结婚了");
}
}
// 调用方法
new My().myMethod();
}
}
// 函数式接口
interface MyBase{
public void myMethod();
}
4、匿名内部类
public class CallTest{
public static void main(String[] args) {
// 匿名内部类
new MyBase(){
@Override
public void myMethod() {
System.out.println("我结婚了");
}
}.myMethod();
}
}
// 函数式接口
interface MyBase{
public void myMethod();
}
5、lambda表达式
public class CallTest{
public static void main(String[] args) {
// lambda表达式
MyBase base = () -> System.out.println("我结婚了");
base.myMethod();
// ((MyBase)() -> System.out.println("我结婚了")).myMethod();
}
}
// 函数式接口
interface MyBase{
public void myMethod();
}
4、lambda表达式语法
- 没有入参
// 单行
Runnable runnable = ()-> System.out.println("1");
// 多行
Runnable runnable1 = ()-> {
System.out.println("1");
System.out.println("2");
};
- 有入参
// 单行
Test test1 = (a,b)-> System.out.println(a);
// 多行
Test test2 = (a,b)-> {
System.out.println(a);
System.out.println(b);
};