Lambda表达式
左侧 Lambda表达式参数列表
右侧 Lambda 表达式中所需执行的功能
语法格式:
- 无参数,无返回值
public class Test {
public static void main(String[] args) {
Runnable r = () -> System.out.println("hello");
r.run();
}
}
- 有一个参数,无返回值
public class Test {
public static void main(String[] args) {
Consumer<String> com = (x) -> System.out.println(x);
com.accept("test");
}
}
- 有一个参数,小括号可以省略不写
public class Test {
public static void main(String[] args) {
Consumer<String> com = x -> System.out.println(x);
com.accept("test");
}
}
- 有两个参数,有返回值,并且有多条语句必须要用大括号括起来
public class Test {
public static void main(String[] args) {
Comparator<Integer> comparator = (x, y) ->{
System.out.println("Hello");
return Integer.compare(x, y);
};
}
}
- Lambda体中只有一条语句,return 和大括号可以不写
public class Test {
public static void main(String[] args) {
Comparator<Integer> comparator = (x, y) -> Integer.compare(x, y);;
}
}
- Lambda表达式参数列表类型可以不写,写必须写完,JVM可以通过上下文推断数据类型
public class Test {
public static void main(String[] args) {
Comparator<Integer> comparator = (Integer x, Integer y) ->{
System.out.println("Hello");
return Integer.compare(x, y);
};
}
}
前提 lambda需要“函数式接口”
函数式接口:接口中有一个抽象方法的接口,称为函数式接口。可以用注解 @FunctionalInterface 修饰
可以检查是否式函数式接口。
总结
左右遇一括号省略,左侧推断类型省。