概述
- JDK8 提供的函數式接口
- 提供一個抽象方法test, 接受一個參數, 根據這個參數進行一些判斷, 返回判斷結果 true / false
- 提供幾個默認的default方法, and, or, negate 用於進行組合判斷
- 在流中被廣泛使用
test 方法
/**
* 接收一個參數, 判斷這個參數是否匹配某種規則, 匹配成功返回true, 匹配失敗則返回false
*/
boolean test(T t);
and 方法
/**
* default方法, 接收另外一個Predicate<T>類型參數進行邏輯與操作
* 返回一個新的Predicate
* Predicate<T> newPredicate = (t) -> this.test(t) && other.test(t);
* 如果傳入的Predicate爲空, 會拋出空指針異常
*/
default Predicate<T> and(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) && other.test(t);
}
or 方法
/**
* default方法, 接收另外一個Predicate<T>類型參數進行邏輯或操作
* 返回一個新的Predicate
* Predicate<T> newPredicate = (t) -> this.test(t) || other.test(t);
* 如果傳入的Predicate爲空, 會拋出空指針異常
*/
default Predicate<T> or(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) || other.test(t);
}
negate 方法
/**
* default方法, 返回當前Predicate取反操作之後的Predicate
* Predicate<T> newPredicate = (t) -> !test(t);
*/
default Predicate<T> negate() {
return (t) -> !test(t);
}
isEqual 方法
/**
* 接收一個Object targetRef, 返回一個Predicate<T>類型
* 返回的Predicate的test方法是用來判斷傳入的參數是否等於targetRef
* 如Predicate<T> predicate = Predicate.isEqual("七夜雪");
* 等同於Predicate<T> predicate = t -> "七夜雪".equals(t);
* 個人感覺這個方法沒多大用處
*/
static <T> Predicate<T> isEqual(Object targetRef) {
return (null == targetRef)
? Objects::isNull
: object -> targetRef.equals(object);
}
API 使用樣例
/**
* @author 七夜雪
* @date 2019-01-12 10:53
*/
public class PredicateTest {
// 輔助打印方法
private static void print(Object obj) {
System.out.println(obj);
}
public static void main(String[] args) {
Predicate<String> predicate = item -> "七夜雪".equals(item);
// 1. test 方法測試
System.out.println("1---> " + predicate.test("七夜雪"));
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
// 2. Predicate 返回一個List中的偶數
// list.stream(), 表示將List作爲流進行處理, filter()方法接收一個Predicate, toArray是將流轉換成數組
Object[] result = list.stream().filter(t -> t % 2 == 0).toArray();
print("2---> " + Arrays.toString(result));
// 3. 測試Predicate的and方法, 打印list中大於3, 小於6的數字
Predicate<Integer> predicate1 = t -> t > 3;
predicate1 = predicate1.and(t -> t < 6);
result = list.stream().filter(predicate1).toArray();
print("3---> " + Arrays.toString(result));
// 4. 測試Predicate的or方法, 打印list中小於3或大於5的數字
predicate1 = t -> t < 3;
predicate1 = predicate1.or(t -> t > 5);
result = list.stream().filter(predicate1).toArray();
print("4---> " + Arrays.toString(result));
// 5. 測試Predicate的negate方法, 返回list中大於等於3,小於等於5的數字, 即對場景4取反
result = list.stream().filter(predicate1.negate()).toArray();
print("5---> " + Arrays.toString(result));
// 6. 測試靜態方法isEqual方法, 個人感覺這個方法沒啥用處
predicate = Predicate.isEqual("七夜雪");
print("6---> " + predicate.test("七夜雪"));
print("6---> " + predicate.test("七夜雪1"));
}
}
輸出結果:
1—> true
2—> [2, 4, 6, 8, 10]
3—> [4, 5]
4—> [1, 2, 6, 7, 8, 9, 10]
5—> [3, 4, 5]
6—> true
6—> false