lambda表达式的基础语法 java8引入的新的操作符 “->” 该操作符称为箭头操作符和lambda操作符
箭头操作符将lambda表达式拆成两部分:
左侧: lambda 表达式的所有参数
右侧: lambda 所需执行的功能,即landba体
语法格式一:无参数 无返回值
- ()-> System.out.println(“hello lamdba”);
@Test
public void test1() {
Runnable r1 = new Runnable() {
@Override
public void run() {
System.out.println("hello world");
}
};
r1.run();
System.out.println("-----------------");
Runnable r2 = () -> System.out.println("hello lambda");
r2.run();
}
语法格式二:有参数 无返回值
- (x) -> System.out.println(x);
@Test
public void test2() {
Consumer<String> con = (x) -> System.out.println(x);
con.accept("努力努力努力努力努力");
}
语法格式三:若只有一个参数 小括号可以省略不写
- x -> System.out.println(x);
@Test
public void test3() {
Consumer<String> con1 = x -> System.out.println(x);
con.accept("张艺兴---努力努力努力努力努力");
}
语法格式四:有两个以上的参数,有返回值,并且lamdba有多条语句
- Comparator com = (x,y) -> {
System.out.println(“函数式接口”);
return Integer.compare(x, y);
}
@Test
public void test3() {
Comparator<Integer> com = (x,y) -> {
System.out.println("函数式接口");
return Integer.compare(x, y);
};
语法格式五:当 Lambda 体只有一条语句时,return 与大括号可以省略
- BinaryOperator bo = (x,y) -> x+y;
@Test
public void test3() {
BinaryOperator<Long> bo = (x,y) -> x+y;
}
语法格式六:Lambda参数列表的数据类型可以不写,因为jvm编译器会根据上下文推断出数据类型 即:”类型推断“
- Comparator com = (Integer x, Integer y) -> Integer.compare(x, y);
@Test
public void test4() {
Comparator<Integer> com = (Integer x, Integer y) -> Integer.compare(x, y);
}
总结
上联:左右遇一括号省
下联:左侧推断类型省
横批:能省则省
Landba表达式需要“函数式接口”的支持
函数式接口:接口中只有一个抽象方法的接口,称为“函数式接口”可以使用注解@FunctionalInterface
修饰,可以检查是否是函数式接口