java8中的Lambda表达式

Lambda 表达式基础语法

定义:Lambda 允许把函数作为一个方法的参数(函数作为参数传递到方法中)
1:Lambda 的操作符 “->”,箭头操作符将java8 拆分成了两部分,1:箭头左侧:表达式的参数列表,2:箭头右侧:Lambda 表达式中所需执行的功能,即Lambda体;
1.1:接口的抽象方法是:无参数-》无返回值
eg:
//普通的写法 new Runnable() { @Override public void run() { System.out.println("2333333"); } }.run(); //java8 Runnable r = () -> System.out.println("2333333"); r.run();
1.2:接口的抽象方法是:有一个参数-》无返回值
//@FunctionalInterface 函数式接口 Consumer<String> cob = (x) -> System.out.println("66666666666"+x); cob.accept("裏賓捨");
1.3:接口的抽象方法是:有两个以上参数,有返回值,并且方法体中有多条语句
Comparator<Integer> com = (x,y) -> { System.out.println("dkhsd"); return x + y; }; Integer a = com.compare(1, 2); System.out.println(a); }
1.4:如果lambda体中只有一条语句,那么return和{}都可以省略
Comparator<Integer> com = (x,y) -> Integer.compare(x, y); System.out.println(com.compare(52, 8)); }
1.5:Lamdba 表达式的参数列表的数据类型可以省略不写,因为JVM编译器可以通过上下文推断出,既:“类型推断”
(Integer x,Integer y)->(x,y);
2:lambda 表达式需要函数式接口的支持
2.1;接口中只有一个抽象方法的接口,称为函数式接口。可以使用注解 @FunctionalInterface 修饰,可以检查是否是函数是接口。

posted on 2020-11-01 00:57  夜空中闪闪发光的星星  阅读(183)  评论(0)    收藏  举报