java - 在 groovy 中应用一些谓词到流过滤器

标签 java groovy java-stream

我在 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/

相关文章:

java - 如果用户单击 IE 或 websphere Portal 上的 mozilla 中的新选项卡,如何启动新 session ?

java - Rabbit mq错误: Getting Exception in thread "main" java. io.IOException由: com.rabbitmq.client.ShutdownSignalException引起

Groovydoc 生成空白文档

java - Stream.dropWhile() 不会在两个不同的值中返回正确的值

java - 尽管有 list ,但在 jar 文件中找不到主类

java - JSP/Servlet 中的隐藏表单

xml - Groovy RPC和Magento API:product_attribute.create和无效的请求参数

sql - 动态访问grails中groovy类中的DataSource

java - 将具有条件逻辑的多个 for 循环转换为 Java 8 流

java - 如何访问流中的 getter 和 setter