不带,以及带参数,带返回值的Lambda表达式
无参数无返回值
package com.wcy; //lambda推导必须存在类型 public class Lambda { //静态内部类 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(); //局部内部类 class Like3 implements ILike{ public void lambda() { System.out.println("I like lambda3"); } } like = new Like3(); like.lambda(); //匿名内部类 like = new ILike() { public void lambda() { System.out.println("I like lambda4"); } }; like.lambda(); //lambda like = ()->{ System.out.println("I like lambda5"); }; like.lambda(); } } interface ILike{ void lambda(); } //外部类 class Like implements ILike{ @Override public void lambda() { System.out.println("I like lambda1"); } }
带参数
package com.wcy; public class Lambda2{ public static void main(String[] args) { ILove love=(int a)->{ //可以省略int,自定跟接口匹配。只有一个参数的时候()也可以省略,如果只有一行代码,{ }也可以省略! System.out.println("i love lambda "+a); }; love.lambda(100); love=(a)->{ //省略int 自定跟接口匹配 System.out.println("i love lambda "+a); }; love.lambda(99); love=a->{ //只有一个参数的时候 ()也可以省略 System.out.println("i love lambda "+a); }; love.lambda(98); } } interface ILove{ void lambda(int a); }
带参数的带返回值的
package com.wcy; public class Lambda3 { public static void main(String[] args) { ILove love=(int a,int b)->{ System.out.println("i love lambda "+(a+b)); return a+b; }; System.out.println(love.lambda(100,200)); } } interface ILove{ int lambda(int a,int b); }
带参数的带返回值的
package com.wcy; public class Lambda3 { public static void main(String[] args) { ILove love=(int a,int b)->{ System.out.println("i love lambda "+(a+b)); return a+b; }; love.lambda(12, 16); love=(a,b)->{ System.out.println("i love lambda "+(a+b)); return a+b; }; love.lambda(12, 10); love=(a,b)->{ return a+b; }; System.out.println(love.lambda(12, 8)); love=(a,b)->a+b; System.out.println(love.lambda(12, 6)); } } interface ILove{ int lambda(int a,int b); }