如何在 Java 中將 lambda 表示式作為方法引數傳遞?


lambda 表示式是 Java 中的匿名無名方法。它不會自行執行,用於實現函式式介面中宣告的方法。如果我們想將 lambda 表示式作為方法引數傳遞給 Java,那麼接收的方法引數型別必須為函式式介面型別

示例

interface Algebra {
   int operate(int a, int b);
}
enum Operation {
   ADD, SUB, MUL, DIV
}
public class LambdaMethodArgTest {
   public static void main(String[] args) {
      print((a, b) -> a + b, Operation.ADD);
      print((a, b) -> a - b, Operation.SUB);
      print((a, b) -> a * b, Operation.MUL);
      print((a, b) -> a / b, Operation.DIV);
   }
   static void print(Algebra alg, Operation op) {
      switch (op) {
         case ADD:
            System.out.println("The addition of a and b is: " + alg.operate(40, 20));
            break;
         case SUB:
            System.out.println("The subtraction of a and b is: " + alg.operate(40, 20));
            break;
         case MUL:
            System.out.println("The multiplication of a and b is: " + alg.operate(40, 20));
            break;
         case DIV:
            System.out.println("The division of a and b is: " + alg.operate(40, 20));
            break;
         default:
            throw new AssertionError();
      }
   }
}

輸出

The addition of a and b is: 60
The subtraction of a and b is: 20
The multiplication of a and b is: 800
The division of a and b is: 2

更新日期:2019 年 12 月 19 日

7K+ 瀏覽次數

開啟你的職業生涯

完成課程即可獲得認證

開始學習
廣告