概述
- 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