有没有办法将 Groovy 的 collect 方法与另一个迭代器函数结合使用? [英] Is there any way to leverage Groovy's collect method in combination with another iterator function?
问题描述
例如,groovy File 类有一个很好的将仅过滤出目录而不是文件的迭代器:
For example, the groovy File class has a nice iterator that will filter out just directories and not files:
void eachDir(Closure closure)
当我使用 eachDir
时,我必须先使用创建集合并附加到它的详细方法:
When I use eachDir
, I have to use the verbose method of creating the collection first and appending to it:
def collection = []
dir1.eachDir { dir ->
collection << dir
}
有什么办法让它恢复到漂亮的紧凑收集语法吗?
Any way to get it back to the nice compact collect syntax?
推荐答案
我不知道有什么惯用的"方式来做这件事,好谜语!=D
I don't know of any "idiomatic" way of doing this, nice riddle! =D
您可以尝试将 eachDir
或任何类似的函数传递给将收集其迭代的函数:
You can try passing the eachDir
, or any similar function, to a function that will collect its iterations:
def collectIterations(fn) {
def col = []
fn {
col << it
}
col
}
现在您可以将其用作:
def dir = new File('/path/to/some/dir')
def subDirs = collectIterations(dir.&eachDir)
def file = new File('/path/to/some/file')
def lines = collectIterations(file.&eachLine)
(最后一个例子等价于 file.readLines()
)
(that last example is equivalent to file.readLines()
)
并且仅针对奖励积分,您可以将此函数定义为Closure
类中的方法:
And only for bonus points, you may define this function as a method in the Closure
class:
Closure.metaClass.collectIterations = {->
def col = []
delegate.call {
col << it
}
col
}
def dir = new File('/path/to/some/dir')
def subDirs = dir.&eachDir.collectIterations()
def file = new File('/path/to/some/file')
def lines = file.&eachLine.collectIterations()
更新:另一方面,您也可以这样做:
Update: On the other hand, you might also do:
def col = []
someDir.eachDir col.&add
我认为这不太复杂,但它没有按照您的要求利用 collect
方法:)
Which I think is quite less convoluted, but it's not leveraging the collect
method as you requested :)
这篇关于有没有办法将 Groovy 的 collect 方法与另一个迭代器函数结合使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!