一、记忆点
- lamda表达式出现的目的:简化程序。简化且只能简化函数式接口。
- java是面向对象编程,抨击了C语言这种“面向过程”编程,不存在单独的函数。但是发现有时候使用单独的函数更好,所以借用函数式接口(一个只包含一个抽象方法的接口)实现单独的函数。所以说学术是个圈呐。
我们的Runnable接口就是一个函数式接口。所以开线程的时候可以直接这样用:
new Thread(()->{
for(int i=1; i<100; i++){
System.out.println(i);
}
});
二、lamda表达式的推导和使用
一个类实现了函数式接口,这个类只用一次,如何简化代码呢?
不简化-> static内部类 ->局部内部类->匿名内部类 ->lamda表达式
public class lambda {
//2.static内部类
static class WaveLine implements IDrawSplitLine{
@Override
public void draw() {
System.out.println("~~~~~~~~~~~~~~~~~~~~");
}
}
public static void main(String[] args) {
IDrawSplitLine line;
//测试普通实现类
line = new SolidLine();
line.draw();
//测试static内部类
line = new WaveLine();
line.draw();
//测试局部内部类
//3. 局部内部类
class DottedLine implements IDrawSplitLine{
@Override
public void draw() {
System.out.println("- - - - - - - - - - ");
}
}
line = new DottedLine();
line.draw();
//4.测试匿名内部类
line = new IDrawSplitLine(){
@Override
public void draw() {
System.out.println("///");
}
};
line.draw();
//5.测试lambda表达式
line = () -> {
System.out.println("55555555555555555555");
};
line.draw();
}
}
// 函数式接口
interface IDrawSplitLine{
void draw();
}
//1.普通实现类
class SolidLine implements IDrawSplitLine{
@Override
public void draw() {
System.out.println("————————————————————");
}
}
解释:
对比:我们来看一下,什么都不简化和用lambda表达式简化的对比。
三、lambda表达式的进一步化简
对于带形参的函数构成的函数式接口,我们有如下3种简化方式:
public class Lambda2 {
public static void main(String[] args) {
IDrawSplitLine2 line;
//不化简的lambda表达式
line = (String think) -> {
System.out.println(think);
};
line.draw("Goals made by your own still can be seen as a sprint(短跑冲刺)");
//简化1:去掉形参的类型
line = (think) -> {
System.out.println(think);
};
line.draw("Goals made by your own still can be seen as a sprint(短跑冲刺)");
//简化2:去掉形参的括号: (仅限于只有一个形参时
line = think -> {
System.out.println(think);
};
line.draw("Goals made by your own still can be seen as a sprint(短跑冲刺)");
//简化3:去掉花括号 (仅限于方法的实现只有一行代码时
line = think -> System.out.println(think);
line.draw("Goals made by your own still can be seen as a sprint(短跑冲刺)");
}
}
// 函数式接口
interface IDrawSplitLine2{
void draw(String think);
}