如何使用 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.