为了简化代码的书写,简洁的java语法lambda下面介绍下。
lambda 表达式的语法格式如下:
1 2 3 | (parameters) -> expression 或 (parameters) ->{ statements; } |
下面推导和简化过程步骤:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | public class TestLambda { //2.静态内部类 static class Like1 implements ILike{ @Override public void lambda() { System.out.println("i like lambda 1"); } } public static void main(String[] args) { Like like = new Like(); like.lambda(); Like1 like1 = new Like1(); like1.lambda(); //3.局部内部类 class Like2 implements ILike{ @Override public void lambda() { System.out.println("i like lambda 2"); } } Like2 like2 = new Like2(); like2.lambda(); //3.匿名捏不了,没有类名称,必须借助接口或者父类。 ILike like3 = new ILike() { @Override public void lambda() { System.out.println("i like lambda 3"); } }; like3.lambda(); //用lambda简化 ILike like4 = ()-> {System.out.print("i like lambda 4");}; like4.lambda(); //用lambda简化 ILike like5= ()-> System.out.print("i like lambda 5"); like5.lambda(); //带参数的lambda使用 Test1 test1 = (int a,int b)->{ System.out.print("结果:"+(a+b));}; test1.operation(3,5); //结果:8 Test1 test2 = (c,d)->{ System.out.print("结果:"+(c+d));}; test2.operation(3,5);//结果:8 } } interface ILike{ void lambda(); } //1.外部类使用 class Like implements ILike{ @Override public void lambda() { System.out.println("i like lambda 语法"); } } interface Test1{ void operation(int a,int b); } |