烟台专业网站推广,安徽省建设工程信息网站,建设部安全员证书查询网站,最好的网站设计公司源码 phpjava 8中 predicate chain的使用简介Predicate是一个FunctionalInterface#xff0c;代表的方法需要输入一个参数#xff0c;返回boolean类型。通常用在stream的filter中#xff0c;表示是否满足过滤条件。boolean test(T t);基本使用我们先看下在stream的filter中怎么使用P…java 8中 predicate chain的使用简介Predicate是一个FunctionalInterface代表的方法需要输入一个参数返回boolean类型。通常用在stream的filter中表示是否满足过滤条件。boolean test(T t);基本使用我们先看下在stream的filter中怎么使用PredicateTestpublic void basicUsage(){List stringListStream.of(a,b,c,d).filter(s - s.startsWith(a)).collect(Collectors.toList());log.info({},stringList);}上面的例子很基础了这里就不多讲了。使用多个Filter如果我们有多个Predicate条件则可以使用多个filter来进行过滤public void multipleFilters(){List stringListStream.of(a,ab,aac,ad).filter(s - s.startsWith(a)).filter(s - s.length()1).collect(Collectors.toList());log.info({},stringList);}上面的例子中我们又添加了一个filter在filter又添加了一个Predicate。使用复合PredicatePredicate的定义是输入一个参数返回boolean值那么如果有多个测试条件我们可以将其合并成一个test方法Testpublic void complexPredicate(){List stringListStream.of(a,ab,aac,ad).filter(s - s.startsWith(a) s.length()1).collect(Collectors.toList());log.info({},stringList);}上面的例子中我们把s.startsWith(a) s.length()1 作为test的实现。组合PredicatePredicate虽然是一个interface但是它有几个默认的方法可以用来实现Predicate之间的组合操作。比如Predicate.and(), Predicate.or(), 和 Predicate.negate()。下面看下他们的例子Testpublic void combiningPredicate(){Predicate predicate1 s - s.startsWith(a);Predicate predicate2 s - s.length() 1;List stringList1 Stream.of(a,ab,aac,ad).filter(predicate1.and(predicate2)).collect(Collectors.toList());log.info({},stringList1);List stringList2 Stream.of(a,ab,aac,ad).filter(predicate1.or(predicate2)).collect(Collectors.toList());log.info({},stringList2);List stringList3 Stream.of(a,ab,aac,ad).filter(predicate1.or(predicate2.negate())).collect(Collectors.toList());log.info({},stringList3);}实际上我们并不需要显示的assign一个predicate只要是满足predicate接口的lambda表达式都可以看做是一个predicate。同样可以调用andor和negate操作List stringList4 Stream.of(a,ab,aac,ad).filter(((Predicate)a - a.startsWith(a)).and(a - a.length() 1)).collect(Collectors.toList());log.info({},stringList4);Predicate的集合操作如果我们有一个Predicate集合我们可以使用reduce方法来对其进行合并运算Testpublic void combiningPredicateCollection(){List allPredicates new ArrayList();allPredicates.add(a - a.startsWith(a));allPredicates.add(a - a.length() 1);List stringList Stream.of(a,ab,aac,ad).filter(allPredicates.stream().reduce(x-true, Predicate::and)).collect(Collectors.toList());log.info({},stringList);}上面的例子中我们调用reduce方法对集合中的Predicate进行了and操作。总结本文介绍了多种Predicate的操作希望大家在实际工作中灵活应用。欢迎关注我的公众号:程序那些事更多精彩等着您更多内容请访问 www.flydean.com