Lamda表达式(函数式编程)
- 避免匿名内部类定义过多
- 可以让代码更简洁
- 去掉没有意义的代码,只留下核心的逻辑
1.Function Interface(函数式接口)
- 如果只包含唯一一个抽象方法,它就是一个函数式接口
2.Lambda表达式转变过程:
- 接口
- 实现类
- 静态内部类
- 局部内部类
- 匿名内部类
- Lambda
public class LanbdaDemo01 {
//3.静态内部类
static class LambdaImpl02 implements Lambda{
@Override
public void like() {
System.out.println("l like Lambda02");
}
}
public static void main(String[] args) {
//2.实现类
Lambda lambda01 = new LambdaImpl01();
lambda01.like();
//3.静态内部类
Lambda lambda02 = new LambdaImpl02();
lambda02.like();
//4.局部内部类
class LambdaImpl03 implements Lambda{
@Override
public void like() {
System.out.println("l like Lambda03");
}
}
Lambda lambda03 = new LambdaImpl03();
lambda03.like();
//5.匿名内部类
Lambda lambda04 = new Lambda() {
@Override
public void like() {
System.out.println("l like Lambda04");
}
};
lambda04.like();
//6.lambda
Lambda lambda05 = ()->{
System.out.println("l like Lambda05");
};
lambda05.like();
}
}
//1.接口
interface Lambda{
void like();
}
//2.实现类
class LambdaImpl01 implements Lambda{
@Override
public void like() {
System.out.println("l like Lambda01");
}
}
Java
Copy
3.Lambda表达式简化:
public class LambdaSimplify {
public static void main(String[] args) {
//1.test01
Lover lover01 = (int a)->{
System.out.println("喜欢你"+a);
};
lover01.like(520);
//2.test02(基本写法)
Lover lover02 = (a)->{
System.out.println("喜欢你"+a);
};
lover02.like(520);
//3.test03
Lover lover03 = a->{
System.out.println("喜欢你"+a);
};
lover03.like(520);
//4.test04
Lover lover04 = a->System.out.println("喜欢你"+a);
lover04.like(520);
}
}
interface Lover{
void like(int a);
}
Java
Copy
4.基本写法:
Lover lover02 = (a)->{
System.out.println("喜欢你"+a);
};
网友评论