前言:学习自https://www.bilibili.com/video/BV1V4411p7EF?p=10
Lambda表达式
1、介绍
为 Java 8 新特性
2、5步简化,最终精简为Lambda表达式
//推导Lambda表达式
public class TestLambda1 {
//3.静态内部类
static class Like2 implements ILike {
@Override
public void lambda() {
System.out.println("I like lambda2");
}
}
public static void main(String[] args) {
ILike like = new Like();
like.lambda();
like = new Like2();
like.lambda();
//4.局部内部类
class Like3 implements ILike {
@Override
public void lambda() {
System.out.println("I like lambda3");
}
}
like = new Like3();
like.lambda();
//5.匿名内部类
like = new ILike() {
@Override
public void lambda() {
System.out.println("I like lambda4");
}
};
like.lambda();
//6.用lambda简化
like = ()-> {
System.out.println("I like lambda5");
};
like.lambda();
}
}
//1.定义一个函数式接口
interface ILike {
void lambda();
}
//2.实现类
class Like implements ILike {
@Override
public void lambda() {
System.out.println("I like lambda");
}
}
3、Lambda表达式的再次简化
//Lambda表达式的再次简化
public class TestLambda2 {
public static void main(String[] args) {
//1.lambda表示简化
ILove love = (name)->{
System.out.println("I love -->" + name);
};
//简化1.去掉参数类型
love = (name)-> {
System.out.println("I love -->" + name);
};
//简化2.去掉括号(只有一个参数的情况)
love = name-> {
System.out.println("I love -->" + name);
};
//简化3.去掉花括号(只有一条语句的情况)
love = name-> System.out.println("I love -->" + name);
love.love("Java");
}
}
interface ILove {
void love(String name);
}