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