简介
核心方法 boolean test(T t) : 数据验证,返回布尔类型的值。
源码分析
@FunctionalInterface
public interface Predicate<T> {
//传入参数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);
}
}
使用示例
@ApiModel(value = "Predicate")
public class PredicateDemo1 {
@Test
@ApiModelProperty(value = "predicate.test方法")
public void predicateTest () {
boolean flag = predicateTrueOrFalse("wangjiesheng", s->s.equals("wangjiesheng"));
Console.log("predicateTest-->{}", flag);
//输出:predicateTest-->true
}
public <T> boolean predicateTrueOrFalse (T t, Predicate<T> predicate) {
return predicate.test(t);
}
@Test
@ApiModelProperty(value = "predicate.and.test 方法")
public void predicateAndTest () {
boolean flag = predicateAnd("wangjiesheng", s->s.equals("wangjiesheng"), s -> s.length() == 12);
Console.log("predicateAndTest-->{}", flag);
//输出:predicateAndTest-->true
flag = predicateAnd("wangjiesheng", s->s.equals("wangjiesheng"), s -> s.length() == 11);
Console.log("predicateAndTest-->{}", flag);
//输出:predicateAndTest-->false
}
//先执行predicate,再执行predicate2 and连接 两者必须都是true 结果才是true
public <T> boolean predicateAnd (T t, Predicate<T> predicate, Predicate<T> predicate2) {
return predicate.and(predicate2).test(t);
}
@Test
@ApiModelProperty(value = "predicate.or.test 方法")
public void predicateOrTest () {
boolean flag = predicateOr("wangjiesheng", s->s.equals("wangjiesheng"), s -> s.length() == 12);
Console.log("predicateOrTest-->{}", flag);
//输出:predicateOrTest-->true
flag = predicateOr("wangjiesheng", s->s.equals("wangjiesheng"), s -> s.length() == 11);
Console.log("predicateOrTest-->{}", flag);
//输出:predicateOrTest-->true
}
//先执行predicate,再执行predicate2 or连接 其中有一个是true 结果就是true
public <T> boolean predicateOr (T t, Predicate<T> predicate, Predicate<T> predicate2) {
return predicate.or(predicate2).test(t);
}
@Test
@ApiModelProperty(value = "predicate.negate.test 方法")
public void predicateNegateTest () {
boolean flag = predicateNegate("wangjiesheng", s->s.equals("wangjiesheng"));
Console.log("predicateNegateTest-->{}", flag);
//输出:predicateNegateTest-->false
}
//执行predicate 取反操作
public <T> boolean predicateNegate (T t, Predicate<T> predicate) {
return predicate.negate().test(t);
}
}
总结
使用Predicate可以让你的判断逻辑代码更加的简洁和解耦,增加了可读性、可测试性,同时符合DRY原则。
DRY原则:(don’t repeat yourself): writing code more than once is not a good fit for a lazy developer ;)It also makes your software more difficult to maintain because it becomes harder to make your business logic consistent。一句话:别写重复代码