我在 java 中找到了解决方案的示例:
things.stream()
.过滤( filtersCollection.stream().reduce(Predicate::or).orElse(t->true) );
我尝试使用 groovy (v2.5.4) 重写它:
List<System> systems = ... //load from db
WellApplicationType appType = params['appType']
Contract contract = params['contract']
List<Predicate> filterCollection = []
if (appType != null)
filterCollection.add({SystemRunlife systemRl -> systemRl.getApplicationType() == appType })
if (contract != null)
filterCollection.add({SystemRunlife systemRl -> systemRl.getContract() == contract})
...
systems.stream()
.map{system -> system.getSystemRunlife()}
.filter(filterCollection.stream().reduce{Predicate.&and}.orElse{t -> false})
仅当谓词列表中有 1 个元素时它才有效。如果我有更多,那么我会收到错误:
No signature of method: Script1$_run_closure3$_closure5.doCall() is applicable for argument types: (Script1$_run_closure1, Script1$_run_closure2) values: [Script1$_run_closure1@7d9367fa, Script1$_run_closure2@70c1c430] Possible solutions: doCall(), doCall(java.lang.Object), findAll(), findAll()
谁能告诉我问题出在哪里吗?
更新:
.filter{systemRl -> filterCollection.stream().allMatch{p -> p.test(systemRl)}}
- 也不起作用。
No signature of method: Script1.test() is applicable for argument types: (com.borets.wedb.entity.SystemRunlife) values: [com.borets.wedb.entity.SystemRunlife-5c0d826a-7f63-1ef5-7b74-bde707a1d814 [new]]
最佳答案
Predicate<SystemRunlife> filter = { systemRl -> true }
for (Predicate<SystemRunlife> systemRunlifePredicate : filterCollection) {
filter = (filter & systemRunlifePredicate)
}
我就是这样组合谓词的。也许有人可以提出更有效的方法。
关于java - 在 groovy 中应用一些谓词到流过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59179251/