Lambda表达式基础语法
“->”: 箭头操作符或Lamdba操作符
左侧:Lambda表达式的参数列表
右侧:Lambda表达式中所需执行的功能,即Lambda体
语法格式一:无参数无返回值
()->System.out.println("Hello Lambda!");
public void test(){
Runnable r = new Runnable(){
public void run(){
System.out.println("Hello world");
}
};
System.out.println("===================");
Runnable r = ()->System.out.println("Hello Lambda");
}
语法格式二:有一个参数,无返回值
private static void test01() {
// Consumer<String> consumer = new Consumer<>() {
// @Override
// public void accept(String s) {
// System.out.println(s);
// }
// };
Consumer<String> consumer = (s)-> System.out.println(s);
consumer.accept("zzz");
}
语法格式三:若只有一个参数,小括号可以省略不写
private static void test01() {
// Consumer<String> consumer = new Consumer<>() {
// @Override
// public void accept(String s) {
// System.out.println(s);
// }
// };
Consumer<String> consumer = s-> System.out.println(s);
consumer.accept("zzz");
}
语法格式四:有两个或两个以上的参数,有返回值,并且Lambda方法体中有多条语句(多条语句要用大括号括住)
public static void test02(){
// Comparator<Integer> com = new Comparator<>() {
// @Override
// public int compare(Integer o1, Integer o2) {
// System.out.println("函数式接口");
// return Integer.compare(o1,o2);
// }
// };
Comparator<Integer> com = (x,y)->{
System.out.println("函数式接口");
return Integer.compare(x,y);
};
int compare = com.compare(5, 3);
System.out.println(compare);
语法格式五:有多个参数,有返回值,Lambda体中有一条语句,return和大括号都可以省略不写
private static void test03() {
Comparator<Integer> com = (x,y)-> Integer.compare(x,y);
int compare = com.compare(5, 3);
System.out.println(compare);
}
语法格式六:Lambda表达式的参数列表的数据类型可以省略不写,因为JVM编译器通过上下文推断出数据类型,即“类型推断”。
总结:
左右遇一括号省
左侧推断类型省
一条语句return省
Lambda表达式需要"函数式接口"的支持
函数式接口:接口中只有一个抽象方法的接口,可以使用@FunctionalInterface修饰,可以检查是否是函数式接口