原 jdk8 Lambda 表达式(一)
版权声明:本文为博主原创文章,请尊重他人的劳动成果,转载请附上原文出处链接和本声明。
本文链接:https://www.91mszl.com/zhangwuji/article/details/1304
public class TestLambda1 {
// 语法格式一:无参数,无返回值
@Test
public void test1(){
Runnable r = () -> System.out.println("AAAA");
r.run();
}
// 语法格式二:有一个参数,并且无返回值
@Test
public void test2(){
Consumer<String> con = (x) -> System.out.println(x);
con.accept("91名师指路");
}
// 语法格式三:若只有一个参数,小括号可以省略不写
@Test
public void test3(){
Consumer<String> con = x -> System.out.println(x);
con.accept("91名师指路 - https://91mszl.com");
}
// 语法格式四:有两个以上的参数,有返回值,并且 Lambda 体中有多条语句
@Test
public void test4(){
Comparator<Integer> com = (x, y) -> {
System.out.println("https://www.91mszl.com");
return Integer.compare(x, y);
};
}
// 语法格式五:若 Lambda 体中只有一条语句, return 和 大括号都可以省略不写
@Test
public void test5(){
Comparator<Integer> com = (Integer x, Integer y) -> Integer.compare(x, y);
}
// 语法格式六:Lambda 表达式的参数列表的数据类型可以省略不写,因为JVM编译器通过上下文推断出,数据类型,即“类型推断”
@Test
public void test6(){
Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
}
}
语法格式一:无参数,无返回值。() -> System.out.println("Hello Lambda!");
语法格式二:有一个参数,并且无返回值。(x) -> System.out.println(x)
语法格式三:若只有一个参数,小括号可以省略不写。x -> System.out.println(x)
语法格式四:有两个以上的参数,有返回值,并且 Lambda 体中有多条语句
语法格式五:若 Lambda 体中只有一条语句, return 和 大括号都可以省略不写。Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
语法格式六:Lambda 表达式的参数列表的数据类型可以省略不写,因为JVM编译器通过上下文推断出,数据类型,即“类型推断”。(Integer x, Integer y) -> Integer.compare(x, y);
函数式接口:接口中只有一个抽象方法的接口,称为函数式接口。 可以使用注解 @FunctionalInterface 修饰可以检查是否是函数式接口。
2021-02-17 22:09:21 阅读(734)
名师出品,必属精品 https://www.91mszl.com