如何在groovy中执行条件collectEntries

The*_*ech 11 collections groovy dictionary

是否有可能像收集一样进行有条件的collectEntries?

tim*_*tes 13

[ a:1, b:2, c:3, d:4 ].findAll { it.value > 2 }
Run Code Online (Sandbox Code Playgroud)

应该这样做


Nat*_*hes 5

它并不像Tim Yates使用findAll那样简洁; 只是备案,您可以使用collectEntries要做到这一点:

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

评估为

[c:3, d:4]
Run Code Online (Sandbox Code Playgroud)

在这个答案中使用"$ {it.key}"是一个错误,键将最终成为GStringImpl类的实例,而不是String.

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]
Run Code Online (Sandbox Code Playgroud)

试图将GroovyStrings等同于普通字符串的代码将评估为false,即使字符串看起来相同,也会导致难以弄清楚的错误.