一、Lambda 表达式的基础语法:
下联:左侧推断类型省
横批:能省则省
二、Lambda 表达式需要函数式接口的支付
函数式接口:若接口中只有一个抽象方法的接口,称为函数式接口,
Java8中引入了一个新操作符“->”,该操作符称为箭头操作符或Lambda操作符上联:左右遇一括号省
箭头操作符将Lambda表达式拆分成两部分:
左侧:Lambda表达式的参数列表
右侧:Lambda表达式中所需要执行的功能,即Lambda体
下联:左侧推断类型省
横批:能省则省
二、Lambda 表达式需要函数式接口的支付
函数式接口:若接口中只有一个抽象方法的接口,称为函数式接口,
可以使用注解@FunctionalInterface 修饰,可以检查是否是函数式接口
//语法格式一:无参数,无返回值 @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!" + num); r1.run(); } //语法格式二:有一个参数,并且无返回值 @Test public void test2() { Consumer<String> con = (x) -> System.out.println(x); con.accept("我大威武!"); } //语法格式三:若只有一个参数, 小括号可以省略不写 @Test public void test3() { Consumer<String> con = x -> System.out.println(x); con.accept("我大威武!"); } //语法格式四:有两个以上参数,有返回值,并且Lambda体中有多条语句,Lambda体必须使用大括号 @Test public void test4(){ Comparator<Integer> comparator=(x,y)->{ System.out.println("函数式接口"); return Integer.compare(x,y); }; } //语法格式五:若Lambda体只有一条语句,return和大括号都可以省略不写 @Test public void test5(){ Comparator<Integer> comparator=(x,y)->Integer.compare(x,y); } /** * 语法格式六:Lambda表达式的参数列表的数据类型可以省略不写, * 因为JVM编译器可以通过上下文推断出数据类型,称为类型推断 */ @Test public void test6(){ Comparator<Integer> comparator=(Integer x,Integer y)->Integer.compare(x,y); } //类型推断举例 @Test public void test7(){ String[] strings={"aaa","bbb","ccc"}; List<String> list=new ArrayList<>(); show(new HashMap<>()); } public void show(Map<String,Integer> map){ } //需求:对一个数进行运算 @Test public void application(){ Integer num = operation(100, (x) -> x * x); System.out.println(num); System.out.println(operation(200,(y)->y+200)); } public Integer operation(Integer num, MyFun myFun){ return myFun.getValue(num); }