[英]Combine Java 8 predicates with disjunction
Suppose I have an array or a list of status, and want to filter a list for elements whose status matches any of the given. 假设我有一个数组或一个状态列表,并且想过滤一个列表,查找状态与给定值匹配的元素。 So I go on creating a predicate. 因此,我继续创建谓词。 I started by initializing it with the comparison to the first, then adding more conditions with or
, which resulted in the minimal predicate but was a lot of code: 我首先通过与第一个比较来初始化它,然后使用or
添加更多条件,这使谓词最少,但代码很多:
Predicate<Rec> predicate = null;
for (SendStatus status : statuss) {
Predicate<Rec> innerPred = nr -> nr.getStatus() == status;
if (predicate == null)
predicate = innerPred;
else
predicate = predicate.or(innerpred);
}
More elegantly, I came up with the following code: 更优雅地讲,我想到了以下代码:
Predicate<Rec> predicate = nr -> false;
for (SendStatus status : statuss) {
predicate = predicate.or(nr -> nr.getStatus() == status);
}
This looks nicer, but has a useless predicate at the beginning of the chain. 这看起来更好,但是在链的开头有一个无用的谓词。 Apache Collections had an AnyPredicate
that could be composed of any number of predicates, and I'm basically looking for a replacement. Apache集合有一个AnyPredicate
,可以由任意多个谓词组成,我基本上是在寻找替代品。
Is this superfluous predicate acceptable? 这个多余的谓词可以接受吗? Is there an even more elegant way to write this? 有没有更优雅的方式来写这个?
How about this, assuming statuss
is a Collection<SendStatus>
: 这个怎么样,假设statuss
是一个Collection<SendStatus>
Predicate<Rec> predicate = nr -> statuss.stream().anyMatch(status -> nr.getStatus() == status);
Or this, if statuss
is a SendStatus[]
: 或者这一点,如果statuss
是SendStatus[]
Predicate<Rec> predicate = nr -> Arrays.stream(statuss).anyMatch(status -> nr.getStatus() == status);
Or do as suggested by @Jerry06 in a comment , which is faster if statuss
is a Set<SendStatus>
, and simpler than streaming collection solution above: 或者按照@ Jerry06在注释中的建议进行操作,如果statuss
是Set<SendStatus>
,则它会更快,并且比上面的流收集解决方案更简单:
Predicate<Rec> predicate = nr -> statuss.contains(nr.getStatus());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.