Java 8 Lambda表示式
阿新 • • 發佈:2018-12-09
Lambda 表示式,也可稱為閉包,是Java8的新特性
Lambda 允許把函式作為一個方法的引數(函式作為引數傳遞進方法中)。
使用 Lambda 表示式可以使程式碼變的更加簡潔緊湊。
語法格式:
(parameters) -> expression
或
(parameters) ->{ statements; }
Java8Tester.java
public class Java8Tester { public static void main(String args[]){ Java8Tester tester = new Java8Tester(); // 型別宣告 MathOperation addition = (int a, int b) -> a + b; // 不用型別宣告 MathOperation subtraction = (a, b) -> a - b; // 大括號中的返回語句 MathOperation multiplication = (int a, int b) -> { return a * b; }; // 沒有大括號及返回語句 MathOperation division = (int a, int b) -> a / b; System.out.println("10 + 5 = " + tester.operate(10, 5, addition)); System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction)); System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication)); System.out.println("10 / 5 = " + tester.operate(10, 5, division)); // 不用括號 GreetingService greetService1 = message -> System.out.println("Hello " + message); // 用括號 GreetingService greetService2 = (message) -> System.out.println("Hello " + message); greetService1.sayMessage("Runoob"); greetService2.sayMessage("Google"); } interface MathOperation { int operation(int a, int b); } interface GreetingService { void sayMessage(String message); } private int operate(int a, int b, MathOperation mathOperation){ return mathOperation.operation(a, b); } }
輸出:
10 + 5 = 15 10 - 5 = 5 10 x 5 = 50 10 / 5 = 2 Hello Runoob Hello Google
Lambda 表示式主要用來定義行內執行的方法型別介面,例如,一個簡單方法介面。在上面例子中,我們使用各種型別的Lambda表示式來定義MathOperation介面的方法。然後我們定義了sayMessage的執行。Lambda 表示式免去了使用匿名方法的麻煩,並且給予Java簡單但是強大的函式化的程式設計能力。
直接在 lambda 表示式中訪問外層的區域性變數:
public class Java8Tester { public static void main(String args[]) { final int num = 1; Converter<Integer, String> s = (param) -> System.out.println(String.valueOf(param + num)); s.convert(2); // 輸出結果為 3 } public interface Converter<T1, T2> { void convert(int i); } }
lambda 表示式的區域性變數可以不用宣告為 final,但是必須不可被後面的程式碼修改(即隱性的具有 final 的語義)
在 Lambda 表示式當中不允許宣告一個與區域性變數同名的引數或者區域性變數。