-
避免了匿名内部类定义过多
-
其实质属于函数式编程的概念
- (params) -> expression
- (params) -> statement
- (params) -> {statements}
a->System.out.println("I like lambda --> " + a);
new Thread(()->System.out.println("多线程")).start();
-
函数式接口的定义:
-
任何接口,如果只包含了唯一一个抽象方法,那么它就是函数式接口
public interface A{ public abstract void play(); }
-
对于函数式接口,可以通过lambda表达式来创建该接口对象
//1.定义一个函数式接口 interface Ilike{ void lambda(); } //2.实现类 class Like implements Ilike{ @Override public void lambda(){ System.out.println("I like lambda 1"); } } public class TestLambda{ //3.静态内部类 static class Like2 implements Ilike{ @Override public void lambda(){ System.out.println("I like lambda 2"); } } public static void main(String[] args){ Like like = new Like(); like.lambda(); Like2 like2 = new Like2(); like2.lambda(); //4.局部内部类 class Like3 implements Ilike{ @Override public void lambda(){ System.out.println("I like lambda 3"); } } Like3 like3 = new Like3(); like3.lambda(); //5.匿名内部类,没有类的名称,必须借助接口或者父类 Ilike like4 = new Ilike(){ @Override public void lambda(){ System.out.println("I like lambda 4"); } }; like4.lambda(); //6.用lambda简化 Ilike like5 = ()->{ System.out.println("I like lambda 5"); }; like5.lambda(); } }
-
lambda表达式简化
//只能是函数式接口 interface ILove{ void love(int a); } //lambda表达式简化 ILove love = (int a)->{ System.out.println("I love you ---> " + a); }; //简化1:去掉参数类型 love = (a)->{ System.out.println("I love you ---> " + a); }; //简化2:去掉括号(只有一个参数才行) love = a->{ System.out.println("I love you ---> " + a); }; //简化3:去掉大括号(只有一行代码才行) love = a->System.out.println("I love you ---> " + a); love.love(520);
-
Lambda表达式
最新推荐文章于 2023-01-20 15:44:19 发布