这里很酷。我需要使用稍微复杂的逻辑过滤一组 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/