如何使用 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP