[英]How can I do a conditional collectEntries in groovy
是否可以像 collect 这样有条件的 collectEntries ?
[ a:1, b:2, c:3, d:4 ].findAll { it.value > 2 }
应该做
It's not as succinct as Tim Yates's answer using findAll ;它不像Tim Yates 使用 findAll 的回答那么简洁; but just for the record, you can use
collectEntries
to do this:但只是为了记录,您可以使用
collectEntries
来做到这一点:
[ 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.在这个答案中使用“${it.key}”是一个错误,键最终将成为 GStringImpl 类的实例,而不是字符串。 The answer itself looks ok in the REPL but if you check what class it is, you can see it is wrong:
答案本身在 REPL 中看起来不错,但是如果您检查它是什么类,您会发现它是错误的:
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.即使字符串看起来相同,试图将 GroovyStrings 等同于普通字符串的代码也会评估为 false,从而导致难以弄清楚的错误。
This should work:这应该有效:
[a:1, b:2, c:3, d:4].collectEntries {
if (it.value > 2)
["${it.key}": it.value]
}
it works now after adding else.添加 else 后它现在可以工作了。 thanks
谢谢
[a:1, b:2, c:3, d:4].collectEntries {
if (it.value > 2){
["${it.key}": it.value]
}else{
[:]
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.