Predicate
Guava
@FunctionalInterface
@GwtCompatible
public interface Predicate<T> extends java.util.function.Predicate<T> {
@CanIgnoreReturnValue
boolean apply(@Nullable T input);
@Override
boolean equals(@Nullable Object object);
@Override
default boolean test(@Nullable T input) {
return apply(input);
}
}
java8
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
default Predicate<T> and(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) && other.test(t);
}
default Predicate<T> negate() {
return (t) -> !test(t);
}
default Predicate<T> or(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) || other.test(t);
}
static <T> Predicate<T> isEqual(Object targetRef) {
return (null == targetRef)
? Objects::isNull
: object -> targetRef.equals(object);
}
}
Predicate是简化版的Function。唯一的区别Predicate返回boolean
简单实例
Predicate<String> lengthLessThen10 = new Predicate<String>() {
public boolean apply(String input) {
return input.length() < 10;
}
};
lengthLessThen10.apply("lessThen10");//false
相当于
Function<Integer, Predicate<String>> lengthLessThen = new Function<Integer, Predicate<String>>() {
public Predicate<String> apply(final Integer input) {
return new Predicate<String>() {
public boolean apply(String str) {
return str.length() < input;
}
};
}
};
lengthLessThen.apply(10).apply("lessThen10");//false
定义了一个 Function,接受 Integer 类型的参数,返回 Predicate 实例;在实例化 Predicate 的时候,我们访问了匿名类外部的变量,也即 Function 实例的 apply 方法的参数,由于 Java 语言的限制,匿名类内部用到的外部变量必须声明为 final
Predicates
Predicates 是 Guava 中与 Predicate 接口配套使用的工具类,提供了一些非常有用的工具类,比如使用 and 和 or 组合多个谓词,还有 not 将谓词的条件取反