有没有办法利用Groovy';s collect方法与另一个迭代器函数结合使用?

有没有办法利用Groovy';s collect方法与另一个迭代器函数结合使用?,groovy,iterator,Groovy,Iterator,例如,groovy类有一个很好的迭代器,它只过滤目录而不过滤文件: void eachDir(Closure closure) 当我使用eachDir时,我必须使用详细的方法,首先创建集合并附加到集合中: def collection = [] dir1.eachDir { dir -> collection << dir } def集合=[] dir1.eachDir{dir-> 收藏我不知道有什么“惯用”的方法可以做到这一点,漂亮的谜语!=D 您可以尝试将

例如,groovy类有一个很好的迭代器,它只过滤目录而不过滤文件:

void eachDir(Closure closure) 
当我使用
eachDir
时,我必须使用详细的方法,首先创建集合并附加到集合中:

def collection = []    
dir1.eachDir { dir ->
  collection << dir
}
def集合=[]
dir1.eachDir{dir->
收藏我不知道有什么“惯用”的方法可以做到这一点,漂亮的谜语!=D

您可以尝试将
eachDir
或任何类似函数传递给将收集其迭代次数的函数:

def collectIterations(fn) {
    def col = []
    fn {
        col << it
    }
    col
}
(最后一个示例相当于
file.readLines()

仅对于奖励积分,您可以将此函数定义为
Closure
类中的方法:

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()
我认为这不太复杂,但它没有像你要求的那样利用
collect
方法:)

我不知道有什么“惯用”的方法可以做到这一点,漂亮的谜语!=D

您可以尝试将
eachDir
或任何类似函数传递给将收集其迭代次数的函数:

def collectIterations(fn) {
    def col = []
    fn {
        col << it
    }
    col
}
(最后一个示例相当于
file.readLines()

仅对于奖励积分,您可以将此函数定义为
Closure
类中的方法:

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()

我认为这不太复杂,但它没有像您所要求的那样利用
collect
方法:)

不是针对您所讨论的特定示例。File.eachDir在我看来是一种奇怪的实现。如果他们实现了迭代器()在文件上,这样您就可以在它们上,而不是只执行闭包的自定义构建的

要获得一个干净的一行程序来完成您想要的任务,最简单的方法是使用listFiles,而不是与findAll结合使用:

dir1.listFiles().findAll { it.directory }
如果你看一下eachDir的实现,你会发现它是在暗中进行的(在这个例子中,你不关心的还有很多)

对于许多类似的情况,inject是一种方法,您希望它具有一个起始值,并在遍历集合时进行更改:

def sum = [1, 2, 3, 4, 5].inject(0) { total, elem -> total + elem }
assert 15 == sum

不是针对您正在讨论的特定示例。File.eachDir在我看来是一种奇怪的实现。如果他们在文件上实现了迭代器(),这样您就可以在其上实现迭代器,而不是在自定义构建的只执行闭包的迭代器上实现,那就太好了

要获得一个干净的一行程序来完成您想要的任务,最简单的方法是使用listFiles,而不是与findAll结合使用:

dir1.listFiles().findAll { it.directory }
如果你看一下eachDir的实现,你会发现它是在暗中进行的(在这个例子中,你不关心的还有很多)

对于许多类似的情况,inject是一种方法,您希望它具有一个起始值,并在遍历集合时进行更改:

def sum = [1, 2, 3, 4, 5].inject(0) { total, elem -> total + elem }
assert 15 == sum

有趣的方法,更新版本是我可能开始使用的。有趣的方法,更新版本是我可能开始使用的。