1 、無參數,無返回值
() -> System.out.println("hello World")
Runnable hello_world = () -> System.out.println("hello World");
hello_world.run(); //控制檯輸出hello World
2 、有參數,無返回值
(x) -> System.out.println("hello "+x)
// 一個參數,無返回值
//(x) -> System.out.println("hello "+x)
//如果只有一個參數,括號可省略,如: x -> System.out.println("hello "+x)
Consumer hello_world1 = (x) -> System.out.println("hello "+x);
hello_world1.accept("PangHao");
3 、多個參數,有返回值
(x,y)->x+y
//多個參數有返回值,附帶代碼塊
//(x,y)->x+y
IntBinaryOperator sumInt = (x, y) -> {
System.out.println(x + "+" + y + "=" + (x + y));
return x + y;
};
//如果單行語句不用寫return和大括號
IntBinaryOperator tComparator = (x, y) -> x + y;
System.out.println(tComparator.applyAsInt(7,8));
4 、數據類型省略
/*
* Lambda 表達式中的參數類型都是由編譯器推斷得出的。
* Lambda 表達式中無需指定類型,程序依然可以編譯,這是因爲 javac 根據程序的上下文,
* 在後臺推斷出了參數的類型。 Lambda 表達式的類型依賴於上下文環境,是由編譯器推斷出來的。這就是所謂的 “類型推斷”
*/
// 04 Lambda 表達式的參數列表的數據類型可以省略不寫,因爲JVM編譯器通過上下文推斷出,數據類型,即“類型推斷”
Comparator<Integer> integerComparator01 = ( Integer x, Integer y) -> Integer.compare(x, y);
System.out.println( integerComparator01.compare(6,5));
//還可以簡化
Comparator<Integer> integerComparator02 = ( x, y) -> Integer.compare(x, y);
System.out.println( integerComparator02.compare(3,5));