Lambda表达式语法
基础语法:‘->’Lambda操作符
* 左侧:Lambda表达式的参数列表 对应接口中方法中的参数列表中的参数(比如nice1中MyPredict这个接口中的方法)
* 右侧:Lambda表达式中所需要执行的功能。 对应接口中方法的实现(比如nice1中MyPredict这个接口中的方法)
*
* 语法格式1:无参数,无返回值 ()->System.out.println("aaa")
* 语法格式2:有一个参数,无返回值
* 语法格式3:只有一个参数小括号可以不写,无返回值
* 语法格式4:两个以上参数,并且Lambda体中多条语句--->test3
* 语法格式5:若Lambda中只有一个语句,return和大括号都可以不写,参数列表中的参数类型可以不写,JVM编译器可以通过上下文推断出类型
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 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | package airycode_java8.nice2; import org.junit.Test; import java.util.Comparator; import java.util.function.Consumer; /** * 基础语法:‘->’Lambda操作符 * 左侧:Lambda表达式的参数列表 对应接口中方法中的参数列表中的参数(比如nice1中MyPredict这个接口中的方法) * 右侧:Lambda表达式中所需要执行的功能。 对应接口中方法的实现(比如nice1中MyPredict这个接口中的方法) * * 语法格式1:无参数,无返回值 ()->System.out.println("aaa") * 语法格式2:有一个参数,无返回值 * 语法格式3:只有一个参数小括号可以不写,无返回值 * 语法格式4:两个以上参数,并且Lambda体中多条语句--->test3 * 语法格式5:若Lambda中只有一个语句,return和大括号都可以不写,参数列表中的参数类型可以不写,JVM编译器可以通过上下文推断出类型 * * * * * * * */ public class TestLambda2 { @Test public void test1(){ int num = 0 ; //jdk1.7之前,必须是final Runnable r = new Runnable() { @Override public void run() { System.out.println( "Hello World" +num); } }; r.run(); System.out.println( "---------------" ); Runnable r1 = ()-> System.out.println( "Hello Lambda" ); r1.run(); } @Test public void test2(){ Consumer<String> con = (x)-> System.out.println(x); con.accept( "airycode" ); } @Test public void test3(){ // Comparator<Integer> com = (x,y)->{ // System.out.println("函数式接口"); // return Integer.compare(x,y); // }; Comparator<Integer> com = (x,y)-> Integer.compare(x,y); Comparator<Integer> com2 = (Integer x,Integer y)-> Integer.compare(x,y); } @Test public void test5(){ //必须这样的写法,不能拆开 String[] strs = { "aaa" , "bbb" }; } @Test public void test6(){ Integer operation = operation( 100 , (x) -> x * x); System.out.println(operation); System.out.println( "----------------" ); Integer operation2 = operation( 200 , (x) -> x + 200 ); System.out.println(operation2); } public Integer operation(Integer num,MyFun myFun){ return myFun.getValue(num); } } package airycode_java8.nice2; /** * Created by admin on 2019/1/2. */ @FunctionalInterface public interface MyFun<T> { public Integer getValue(Integer num); } |
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步