Lambda表达式
Lambda表达式在Java 8之后出现(也有人称其为Lamda,看个人习惯)
其实质是属于函数式编程的概念
- (params)->expression[表达式]
- (params)->statement[语句]
- (params)->{statements}
- a->System.out.println(“Hello Lamda”+a);
- new Thread( ()->System.out.println(“多线程学习”) ).start();
为什么使用Lambda表达式
- 避免匿名内部类定义过多
- 代码看起来更简洁
- 去掉一堆无意义的代码,只留下核心逻辑
函数式接口
定义:任何接口,如果只包含唯一一个抽象方法,那么它就是一个函数式接口
//举例
public interface Runnable{
public abstract void run();
}
对于函数式接口,可以通过Lambda表达式来创建该接口的对象
推导Lambda表达式
//1.函数式接口
public interface FunInter{
void lamda();
}
//2.实现接口
public class FunInterImpl implements FunInter{
@Override
public void lamda(){
System.out.println("Hello Lambda!");
}
}
public class TestLamda{
//3.静态内部类
static class FunInterImpl2 implements FunInter{
@Override
public void lamda(){
System.out.println("Hello Lambda2!");
}
}
public static void main(String[] args){
FunInter fi = new FunInterImpl();
fi.lamda();//Hello Lambda!
fi = new FunInterImpl2();
fi.lamda();//Hello Lambda2!
//4.局部内部类
class FunInterImpl3 implements FunInter{
@Override
public void lamda(){
System.out.println("Hello Lambda3!");
}
}
fi = new FunInterImpl3();
fi.lamda();//Hello Lambda3!
//5.匿名内部类,没有类的名称,必须借助接口或者父类
fi = new FunInter(){
@Override
public void lamda(){
System.out.println("Hello Lambda4!");
}
}
fi.lamda();//Hello Lambda4!
//6.Lambda表达式,简化
fi = ()->{System.out.println("Hello Lambda5!");};
fi.lamda();//Hello Lambda5!
}
}
带一个参数的Lambda简化
public class TestLamda {
public static void main(String[] args) {
FunInter fi = null;
//Lamda简化
fi = (int a)->{
System.out.println("hello"+a);
};
fi.hello(1);//hello1
//Lamda简化参数类型
fi = (a)->{
System.out.println("hello"+a);
};
fi.hello(2);//hello2
//Lamda简化括号
fi = a->{
System.out.println("hello"+a);
};
fi.hello(3);//hello3
//Lamda简化花括号(只有一条语句时才可)
fi = a->System.out.println("hello"+a);
fi.hello(4);//hello4
}
}
//函数式接口
interface FunInter{
void hello(int a);
}
带多个参数的Lambda简化
public class TestLamda02 {
public static void main(String[] args) {
FunInter live = null;
//Lamda简化
FunInter = (int a,int b)->{
System.out.println("hello "+a+","+b);
};
FunInter.hello(1,1);//hello 1,1
//Lamda简化参数类型(若去全去,若留全留)
FunInter = (a,b)->{
System.out.println("hello "+a+","+b);
};
FunInter.hello(2,2);//hello 2,2
//Lamda简化花括号(只有一个语句时)
FunInter = (a,b)->System.out.println("hello "+a+","+b);
FunInter.hello(3,3);//hello 3,3
}
}
interface FunInter{
void hello(int a,int b);
}
总结
- Lambda表达式只能在只有一行代码的情况下才能简化为一行(即去掉花括号{}),若有多行,则必须用代码块包裹
- 使用Lambda表达式的前提是使用的接口为函数式接口
- 出现多个参数时,使用小括号()将参数包裹
- 多个参数也可以去掉参数类型,但需要注意:若去掉,则全去;若要留,则全留