来自 Groovy JDK:
public Collection grep()
Iterates over the collection of items which this Object represents and returns each item that matches using the IDENTITY Closure as a filter - effectively returning all elements which satisfy Groovy truth.
public Collection findAll()
Finds all items matching the IDENTITY Closure (i.e. matching Groovy truth).
最佳答案
简短的回答:结果是一样的。
长答案:grep
通常使用过滤器对象,在该对象上 isCase
然后被调用。因此,grep 的参数通常不是 Groovy 闭包。对于 findAll
你使用一个闭包作为参数,如果闭包的结果被评估为真,它就会被纳入结果集合。
现在重要的是要知道闭包也有一个 isCase 方法。 Closure#isCase(Object)
将使用参数作为闭包的参数来执行闭包,然后使用 Groovy Truth 评估其结果。对于身份关闭,即。 {it}
,这意味着闭包将返回提供给它的内容,因此 Groovy 会将 Groovy Truth 应用于 grep 调用的参数。结果与 findAll 相同。
关于groovy - Groovy 的非参数 grep() 和 findAll() 方法之间有什么区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10703707/