【问题标题】:Apply few Predicates to stream filter in groovy在 groovy 中应用一些谓词来流过滤器
【发布时间】:2019-12-04 15:19:31
【问题描述】:

我在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 个元素时它才有效。如果我有更多,那么我会收到一个错误:

没有方法签名:Script1$_run_closure3$_closure5.doCall() 是 适用于参数类型:(Script1$_run_closure1, Script1$_run_closure2) 值:[Script1$_run_closure1@7d9367fa, Script1$_run_closure2@70c1c430] 可能的解决方案:doCall(), doCall(java.lang.Object), findAll(), findAll()

谁能告诉我哪里出了问题?

更新:

.filter{systemRl -> filterCollection.stream().allMatch{p -> p.test(systemRl)}}

- 也不工作。

没有方法签名:Script1.test() 适用于参数 类型:(com.borets.wedb.entity.SystemRunlife)值: [com.borets.wedb.entity.SystemRunlife-5c0d826a-7f63-1ef5-7b74-bde707a1d814 [新]]

【问题讨论】:

  • 能否请您出示您在那里使用的所有东西的声明?特别是 filterCollection
  • 做到了。但我不确定它是否有帮助。如果我删除第一个或第二个if - 它工作正常。
  • 只需检查我在 java 中的示例 - 工作正常。

标签: java groovy java-stream


【解决方案1】:
Predicate<SystemRunlife> filter = { systemRl -> true }
for (Predicate<SystemRunlife> systemRunlifePredicate : filterCollection) {
    filter = (filter & systemRunlifePredicate)
}

我以这种方式组合了谓词。也许有人可以提出更合理的方式。

【讨论】:

    猜你喜欢
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-04
    相关资源
    最近更新 更多