Is there any way to leverage Groovy's collect method in combination with another iterator function?

后端 未结 2 1047
無奈伤痛
無奈伤痛 2020-12-20 08:13

For example, the groovy File class has a nice iterator that will filter out just directories and not files:

void eachDir(Closure closure) 

2条回答
  •  感情败类
    2020-12-20 08:52

    Not for the specific example that you're talking about. File.eachDir is sort of a weird implementation IMO. It would have been nice if they implemented iterator() on File so that you could use the normal iterator methods on them rather than the custom built ones that just execute a closure.

    The easiest way to get a clean one liner that does what you're looking for is to use listFiles instead combined with findAll:

    dir1.listFiles().findAll { it.directory }
    

    If you look at the implementation of eachDir, you'll see that it's doing this (and a whole lot more that you don't care about for this instance) under the covers.

    For many similar situations, inject is the method that you'd be looking for to have a starting value that you change as you iterate through a collection:

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

提交回复
热议问题