BiPredicate<T,U>接口是java8中用来做对lambda表达式做判断的Function函数,BiPredicate用法非常简单,先看看泛型所表达的意思。
T - 表示第一个参数
U - 表示第二个参数
BiPredicate接口中有4个方法,如下。
//判断是否满足条件 boolean test(T t, U u) //and表示是否同时满足 default BiPredicate<T,U> and(BiPredicate<? super T,? super U> other) //negate表示非运算,类似"!" default BiPredicate<T,U> negate() //or或者 default BiPredicate<T,U> or(BiPredicate<? super T,? super U> other)
1:test(T t, U u)的使用方法,返回true或false:
import java.util.function.BiPredicate;
public class TestDemo {
public static void main(String[] args) {
//lambda表达式:x是否大于y参数
BiPredicate<Integer, Integer> bi = (x, y) -> x > y;
System.out.println(bi.test(2, 3));
}
}输出结果:false。
2:and(BiPredicate<? super T,? super U> other)方法使用,返回BiPredicate对象:
import java.util.function.BiPredicate;
public class TestDemo {
public static void main(String[] args) {
//x是否大于y的lambda表达式
BiPredicate<Integer, Integer> bi = (x, y) -> x > y;
//x减去2之后是否还大于y
BiPredicate<Integer, Integer> an = (x, y) -> x -2 > y;
System.out.println(bi.test(2, 3));
//是否同时满足
System.out.println(bi.and(an).test(4, 3));
System.out.println(bi.and(an).test(8, 3));
}
}输出结果:
false
false
true
3:BiPredicate<T,U> negate()方法的使用,非运算,如果test()的结果为true,则返回false,反之返回true,如下。
import java.util.function.BiPredicate;
public class TestDemo {
public static void main(String[] args) {
//x是否大于y的lambda表达式
BiPredicate<Integer, Integer> bi = (x, y) -> x > y;
System.out.println(bi.test(2, 3));
System.out.println(bi.negate().test(2, 3));
}
}输出结果:
false
true
4:or(BiPredicate<? super T,? super U> other)表示或者,即满足一个条件就会返回true,用法如下。
import java.util.function.BiPredicate;
public class TestDemo {
public static void main(String[] args) {
//x是否大于y的lambda表达式
BiPredicate<Integer, Integer> bi = (x, y) -> x > y;
//x-2是否还大于4
BiPredicate<Integer, Integer> eq = (x, y) -> x -2 > y;
System.out.println(bi.test(2, 3));
System.out.println(bi.or(eq).test(8, 3));
}
}输出结果:
false
true