如何使用 Java 中的 lambda 和方法引用來實現 IntPredicate 介面?


IntPredicate 介面是一個內建的功能介面,定義在 java.util.function 包中。此功能介面接受一個 int 值 作為輸入,併產生一個 boolean 值作為輸出。此介面是 Predicate 介面的專門化,用作 lambda 表示式方法引用 的賦值目標。它只提供一個抽象方法,test()

語法

@FunctionalInterface
public interface IntPredicate {
 boolean test(int value);
}

Lambda 表示式的示例

import java.util.function.IntPredicate;

public class IntPredicateLambdaTest {
   public static void main(String[] args) {
      IntPredicate intPredicate = (int input) -> {   // lambda expression
         if(input == 100) {
            return true;
         } else
            return false;
      };
      boolean result = intPredicate.test(100);
      System.out.println(result);
   }
}

輸出

true


方法引用的示例

import java.util.function.IntPredicate;

public class IntPredicateMethodReferenceTest {
   public static void main(String[] args) {
      IntPredicate intPredicate = IntPredicateMethodReferenceTest::test;   // method reference
      boolean result = intPredicate.test(100);
      System.out.println(result);
   }
   static boolean test(int input) {
      if(input == 50) {
         return true;
      } else
         return false;
   }
}

輸出

false

更新於:13-Jul-2020

326 次瀏覽

開始你的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.