【Java8】Guava——Predicate

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 将谓词的条件取反

这里写图片描述
这里写图片描述

Predicate具体参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值