How can I do a conditional collectEntries in groovy

[ a:1, b:2, c:3, d:4 ].findAll { it.value > 2 }

should do it


It's not as succinct as Tim Yates's answer using findAll; but just for the record, you can use collectEntries to do this:

[ a:1, b:2, c:3, d:4 ].collectEntries { 
    it.value > 2 ? [(it.key) : it.value] : [:] }

which evaluates to

[c:3, d:4]

Using "${it.key}" as done in this answer is an error, the key will end up being an instance of the GStringImpl class, not a String. The answer itself looks ok in the REPL but if you check what class it is, you can see it is wrong:

groovy:000> m = [ a:1, b:2, c:3, d:4 ]
===> [a:1, b:2, c:3, d:4]
groovy:000> m.collectEntries { ["${it.key}" : it.value ] }
===> [a:1, b:2, c:3, d:4]
groovy:000> _.keySet().each { println(it.class) }
class org.codehaus.groovy.runtime.GStringImpl
class org.codehaus.groovy.runtime.GStringImpl
class org.codehaus.groovy.runtime.GStringImpl
class org.codehaus.groovy.runtime.GStringImpl
===> [a, b, c, d]

Code trying to equate GroovyStrings to normal strings will evaluate to false even when the strings look identical, resulting in a hard-to-figure-out bug.