需求
给一个集合,找到满足添加的对象,一下条件可能会动态的变化,有时候只需要满足一个,有时候需要满足两个。。。
1、大于。。
2、小于。。
3、是偶数
Predicate主要作用就是输入一个参数,输出一个
Boolean值,用于判断这个输入的参数是否满足某个条件
Predicate 接口里面 一个默认方法 ,可以完成多个条件的组合
default Predicate<T> and(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) && other.test(t);
}
default Predicate<T> or(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) || other.test(t);
}
测试代码:
public class RequestParam {
private String packageId;
private String data;
private boolean isFlow;
public RequestParam(String packageId, String data, boolean isFlow) {
try {
this.packageId = packageId;
this.data = URLEncoder.encode(data, "UTF-8");
this.isFlow = isFlow;
}catch (Exception e){
e.printStackTrace();
}
}
public String getPackageId() {
return packageId;
}
public String getData() {
return data;
}
public boolean isFlow() {
return isFlow;
}
@Override
public String toString() {
return "packageId="+packageId+"&data="+data+"&isFlow="+isFlow+"";
}
}
public class PredicateTest {
public static void main(String[] args) {
List<RequestParam> list = new ArrayList<>();
RequestParam requestParam1 = new RequestParam("test/111","111",true);
RequestParam requestParam2 = new RequestParam("test/222","222",false);
RequestParam requestParam3 = new RequestParam("test/333","333",false);
list.add(requestParam1);
list.add(requestParam2);
list.add(requestParam3);
Predicate<RequestParam> condition1 = value -> value.getPackageId().startsWith("test") ;
Predicate<RequestParam> condition2 = value -> value.getData().length()==3;
Predicate<RequestParam> condition3 = value -> value.isFlow() == false ;
Predicate<RequestParam> predicate = condition1.and(condition2.or(condition3));
AtomicInteger count= new AtomicInteger();
list.forEach(v -> {
if(predicate.test(v)){
count.getAndIncrement();
}
});
System.out.println("符合帅选条件的数量:"+count);
}
}