Predicate接口源码阅读以及使用

677 阅读1分钟

Predicate接口源码

直接上Predicate源码,Predicate中文翻译“断言”,我们下面就叫它断言接口,称其实现为断言实例。


@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接口应用了@FunctionalInterface接口,注明函数式接口,可以使用拉姆达表达式来进行调用,主要实现

boolean test(T t);

方法,还可以看到接口内部默认实现了三个方法:and,or,negate,都是返回断言实现,这三个方法类似于java三个连接符号&&、||和!,基本使用使用如下:

int[] numbers= {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
		List<Integer> list=new ArrayList<>();
		for(int i:numbers) {
			list.add(i);
		}
		Predicate<Integer> p1=i->i>5;
		Predicate<Integer> p2=i->i<20;
		Predicate<Integer> p3=i->i%2==0;
		List test=list.stream().filter(p1.and(p2).and(p3)).collect(Collectors.toList());
		System.out.println(test.toString());
/** print:[6, 8, 10, 12, 14]*/

如果我们现在想要过滤出奇数呢?

List test=list.stream().filter(p1.and(p2).and(p3.negate())).collect(Collectors.toList());
/** print:[7, 9, 11, 13, 15]*/

isEqual方法返回类型也是Predicate,我们可以当做==操作符来用

		List test=list.stream()
            .filter(p1.and(p2).and(p3.negate()).and(Predicate.isEqual(7)))
            .collect(Collectors.toList());
/** print:[7] */