理解Groovy计数闭包

理解Groovy计数闭包,groovy,closures,Groovy,Closures,我刚开始使用Groovy,虽然最终在Java环境中使用闭包让人耳目一新,但我在让count按我所希望的方式工作时遇到了问题 假设我有一个类Foo,看起来像这样: public class Foo { private boolean isBar; public boolean isBar() { return isBar; } public boolean setIsBar(boolean isBar) { this.isBar

我刚开始使用Groovy,虽然最终在Java环境中使用闭包让人耳目一新,但我在让
count
按我所希望的方式工作时遇到了问题

假设我有一个类
Foo
,看起来像这样:

public class Foo {

    private boolean isBar;

    public boolean isBar() {
        return isBar;
    }

    public boolean setIsBar(boolean isBar) {
        this.isBar = isBar;
    }

}
foos.count { it.isBar() }
现在让我们假设我有一个
列表
Foo
实例,我想计算
Foo
对象的数量,其中
isBar
为真。我希望它看起来像这样:

public class Foo {

    private boolean isBar;

    public boolean isBar() {
        return isBar;
    }

    public boolean setIsBar(boolean isBar) {
        this.isBar = isBar;
    }

}
foos.count { it.isBar() }
或者使用属性表示法,只需:

foos.count { it.bar }
但是,这不会返回预期的结果,它只返回0

我试着用一个简单的int
列表来测试它。要计算2的出现次数,我可以执行以下操作:

[1, 2, 2, 3].count(2)
但是我不应该使用闭包来完成以下操作吗

[1, 2, 2, 3].count { it == 2 }
后者似乎也没有返回预期的结果。我所做的研究似乎表明我所做的是正确的,但显然不是。正确的使用方法是什么?

根据
集合#count(Closure)
直到1.8.0才添加。您可以试试
#sum

assert [1, 2, 2, 3].sum() { it == 2? 1 : 0 } == 2

1.6下的
Collection.count
单据:

数字计数(对象值)

统计给定值在此集合中出现的次数

因此:


1.8下的
Collection.count
单据:

数字计数(对象值)

统计给定值在此集合中出现的次数

计数(关闭)

统计此集合中满足给定闭包的出现次数


这些文档非常非常有用。

在groovy 1.8+中,您可以编写:

[1, 2, 2, 3].iterator().count { it == 2 }
由于向后兼容性,DefaultGroovyMethods的新方法签名为:

public static Number count(Iterator self, Closure closure) {

我使用groovy 1.8.4Granted,我使用1.6.0,因为它是一个较旧的项目,但是如果升级到1.8是不同的,我会感到惊讶。你应该让你的
Foo
类更groovyish<代码>类Foo{booleanbar}
(很难让它在注释中看起来很好…)。Setters/getter会自动为您提供。谢谢Justin——真不敢相信我在文档中遗漏了这一点。我将尝试升级到1.8。@Tyler如果您有问题,请先尝试升级到1.7版,然后再从那里升级到1.8版。尽管版本编号不同,但每次升级都需要对代码进行非常小的调整。计数后的圆括号是可选的。如果使用,则它们会将卷曲夹钳封闭的迭代器执行块括起来。@AlexanderStohr你说的是{括号?你能写出结果代码吗?[1,2,2,3]。迭代器().count({it==2})