使用findAll和groovy中的每一个更新地图 [英] Update map using findAll and each in groovy
本文介绍了使用findAll和groovy中的每一个更新地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在Groovy中更新地图中的值,并填写特定的条件。这里是我的代码:
I would like to update values in map in Groovy filling certain criteria. Here is my code:
def m = [:]
m['a'] = 1
m['b'] = 2
m['d'] = 3
m.findAll { it.value > 1}.each {
it.value = 4
}
println m
但结果如下:
But the result is following:
[a:1, b:2, d:3]
有什么办法可以同时使用findAll和each?或者我必须使用
Is there any way to do it using both findAll and each? Or I must use
m.each {if (it.value>1) it.value=4}
推荐答案
根本原因是 findAll
返回一个新的Map实例。
所以你可以试试:
So you could try:
newMap = m.findAll { it.value > 1}.each {
it.value = 4
}
println m //No change
println newMap //This is what you need!
输出是
output is
[a:1, b:2, d:3]
[b:4, d:4]
这篇关于使用findAll和groovy中的每一个更新地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文