groovy - Groovy findAll 闭包中的复杂过滤逻辑

标签 groovy closures

这里很酷。我需要使用稍微复杂的逻辑过滤一组 Set 网络博彩公司,并且我正在努力理解 findAll 闭包的正确使用。

@Canonical
class Widget {
    String name
    Boolean fizzbuzz
}

...

Set<Widget> filter(Integer isHidden, Set<Widget> inputWidgets) {
    inputWidgets.findAll { widget ->
        Foobar foobar = FoobarHelper.getFoobarByWidget(widget)

        // Logic:
        // If isHidden is 0 and no foorbar exists for the given widget,
        // then we want to add this widget to the collection being
        // returned...
        if(isHidden.intValue() == 0 && !foobar) {
            // Add this widget to collection being returned
            ???
        }

        // ...but if isHidden is 1 and a foobar does exist for the given
        // widget, then we want to add this widget to the collection as
        // well.
        else if(isHidden.intValue() == 1 && foobar) {
            // Add this widget to collection being returned
            ???
        }
    }
}

过滤逻辑又是:

  • 如果 isHidden == 0 并且 FoobarHelper.getFoobarByWidget(...) 返回 null,则添加当前 widget 到正在返回的集合;和
  • 如果 isHidden == 1 并且 FoobarHelper.getFoobarByWidget(...) 返回非 null,则添加当前 小部件到正在返回的集合

认为我的逻辑实现是正确的,我只是在努力解决如何将当前 widget 添加到返回集合(哪里有 ???)。 有什么想法吗?

最佳答案

看起来应该只是:

@Canonical
class Widget {
    String name
    Boolean fizzbuzz
}

...

Set<Widget> filter(Integer isHidden, Set<Widget> inputWidgets) {
    inputWidgets.findAll { widget ->
        Foobar foobar = FoobarHelper.getFoobarByWidget(widget)
        (isHidden.intValue() == 0 && !foobar) || (isHidden.intValue() == 1 && foobar)
    }
}

在这一行中:

(isHidden.intValue() == 0 && !foobar) || (isHidden.intValue() == 1 && foobar)

您正在检查这两个条件。所有满足其中任何一个的元素都将被添加到返回的集合中。

关于groovy - Groovy findAll 闭包中的复杂过滤逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49750472/

相关文章:

javascript - javaScript中的词法作用域/闭包

grails - grails-在查询中使用动态列表

jenkins - Jenkins 管道中的条件步骤/阶段

string - 如何使用 Groovy 脚本将整数转换为指定长度的字符串值

grails - 使用 “and”和 “or”子句时,Grails中的findAll()方法无法正常运行

swift - 在 swift 中捕获闭包的值是否意味着创建静态变量?

mysql - Groovy:解析具有特定扩展名的文件以导入 MySQL,然后将其重命名为 *.bak

java - 如何在 groovy 中收集列表的相似项目

Javascript - setTimeout 关闭问题

c# - 为什么不用 .NET 风格的委托(delegate)而不是 Java 中的闭包?