如何使用Java中的lambda和方法引用来实现IntPredicate接口?
IntPredicate接口是java.util.function包中定义的内置功能接口。该功能接口接受一个int值参数作为输入,并产生一个布尔值作为输出。此接口是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 表达式
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; //方法引用
boolean result = intPredicate.test(100);
System.out.println(result);
}
static boolean test(int input) {
if(input == 50) {
return true;
} else
return false;
}
}输出结果
false