Question: I have a function like this:

```
private downloadAllFiles() {
    sftpRetriever.listFiles().findAll {
        filter.isResponse(it) || filter.isResponseTurned(it)
    }.each { String fileName ->
        log.info 'Downloading file: {}', fileName
        sftpRetriever.downloadFile(fileName)
        log.info 'File downloaded'
        removeRemoteFile(fileName)
    }
}

```

I am looking for a simple way of modyfing this closure inside of that function so if the size() of findAll is 0 it will simply log 'No more files to download' and .each won't be executed. Is there any simple way to make it in single closure? It is really simply task if I divide it in several parts, but trying to learn closures here and improve my expressiveness :) Thank you in advance for your help.

Answer: 
Take a look at creature below :) It works due the fact that [`each`](http://groovy.codehaus.org/api/org/codehaus/groovy/runtime/DefaultGroovyMethods.html#each%28T,%20groovy.lang.Closure%29) returns the collection on which it's invoked (+ [elvis operator](http://groovy.codehaus.org/Operators#Operators-ElvisOperator%28?:%29) and quite nice Groovy's [truth evaluation](http://groovy.codehaus.org/Groovy+Truth)):

```
def printContents(Collection collection) {
    collection.each {
        println it
    } ?: println('Collection is empty')
}

printContents([1,2,'hello'])
printContents([])

```

I don't like this syntax but it's the shorter version which came to my mind.

You can also use [metaprogramming](http://groovy.codehaus.org/ExpandoMetaClass) to add the method provided by Steinar. It must be added to `metaClass` before first use but you'll avoid an effort to make extension module:

```
Collection.metaClass.doIfEmpty { Closure ifEmptyClosure ->
        if (delegate.empty) {
            ifEmptyClosure()
        }
        return delegate
}

def printContents(Collection collection) {
    collection.doIfEmpty {
        println "Collection is empty"
    }.each {
        println it
    }
}

printContents([1,2,'hello'])
printContents([])

```
You may try the following piece of code: 

```
def l1 = [1,2,3,4]
def l2 = [5,6,7,8]

def m(list) {
    list.findAll { it < 5}.with { l ->
        size > 0 ? 
            l.each { e ->
                println e  
            }
        : 
            println('Zero elements found')
    }
}

m(l1)
m(l2)

```

No better idea at the moment.