【发布时间】:2016-10-12 07:29:23
【问题描述】:
假设我有一个数组或一个状态列表,并且想要过滤一个列表以查找其状态与任何给定值匹配的元素。所以我继续创建一个谓词。我首先通过与第一个比较来初始化它,然后使用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);
}
更优雅的是,我想出了以下代码:
Predicate<Rec> predicate = nr -> false;
for (SendStatus status : statuss) {
predicate = predicate.or(nr -> nr.getStatus() == status);
}
这看起来更好,但在链的开头有一个无用的谓词。 Apache Collections 有一个 AnyPredicate 可以由任意数量的谓词组成,我基本上是在寻找替代品。
这个多余的谓词可以接受吗?有没有更优雅的写法?
【问题讨论】:
-
为什么不使用
Predicate<Rec> predicate = nr -> statuss.contains(nr .getStatus()) ;? -
嘿@Jerry06,在这种情况下你是完全正确的(我更改了我的代码以完全使用它)。但是,我让这个问题代表更一般的情况。