写在前面
JDK8 API提供了很多函数式接口,这些函数式接口可以被抽象成一个具体的方法,并且使其使用在Lambda表达式中,今天我们要来说的就是其中的BiPredicate函数接口。
JDK8函数式接口之BiPredicate
今天我们来说一下BiPredicate函数接口,从名称来看,像是从Predicate函数接口演变过来的,具体是如何,一步步的来看看吧。
让我们先来看一下源码,清楚一下具体有哪些方法。
@FunctionalInterface public interface BiPredicate<T, U> { boolean test(T t, U u); default BiPredicate<T, U> and(BiPredicate<? super T, ? super U> other) { Objects.requireNonNull(other); return (T t, U u) -> test(t, u) && other.test(t, u); } default BiPredicate<T, U> negate() { return (T t, U u) -> !test(t, u); } default BiPredicate<T, U> or(BiPredicate<? super T, ? super U> other) { Objects.requireNonNull(other); return (T t, U u) -> test(t, u) || other.test(t, u); } }
从源码上来看,其实和Predicate接口提供的方法差不多,都有and、negate、or方法。
不同的是BiPredicate函数接口多了一个传入参数,使用上也从而多了很多的变化。
public static void main(String[] args) { BiPredicate<String, Integer> biPredicate = (x, y) -> "test".equals(x) && 1 == y; boolean flag1 = biPredicate.test("test", 1); boolean flag2 = biPredicate.test("test", 2); boolean flag3 = biPredicate.test("test1", 2); System.out.print(flag1); System.out.print(flag2); System.out.print(flag3); }
上面的执行结果如下所示:
true false false
and方法
and方法的使用,其实也就是在原来的基础上,进行一个条件的加成。
代码示例如下所示:
biPredicate.and(iPredicate).test("test", 1);
上面的iPredicate对象是一个新的BiPredicate对象,and方法也就是传入了这个新对象。
BiPredicate函数接口还提供了negate、or接口,与Predicate函数接口一样。
negate方法,是取相反的结果。而or是and方法的对立面,从名称上来看,我们就知道是或者的意思了。
总结
今天我们学习了BiPredicate函数接口,大概也了解了其与Predicate接口的方法区别,大家是否在其中学习了什么呢?