如何在 Java 中在方法中傳遞 lambda 表示式?


 lambda 表示式傳入了具有函式式介面型別的引數的一個方法。如果我們需要將 lambda 表示式作為引數傳入,接收 lambda 表示式引數的引數型別必須是函式式介面型別。

在下面的示例中,lambda 表示式可以傳入一個方法,該方法的引數型別為“TestInterface”。

示例

interface TestInterface {
   boolean test(int a);
}
class Test {
   // lambda expression can be passed as first argument in the check() method
   static boolean check(TestInterface ti, int b) {
      return ti.test(b);
   }
}
public class LambdaExpressionPassMethodTest {
   public static void main(String arg[]) {
      // lambda expression
      boolean result = Test.check((x) -> (x%2) == 0, 10);
      System.out.println("The result is: "+ result);
   }
}

輸出

The result is: true

更新於: 2020-07-10

3 千多瀏覽

啟動你的 職業生涯

完成課程獲得認證

立即開始
廣告
© . All rights reserved.