Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update map using findAll and each in groovy

Tags:

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]

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}
like image 255
Krzysztof Kazmierczyk Avatar asked Dec 09 '13 21:12

Krzysztof Kazmierczyk


2 Answers

The root cause is findAll returns a new Map instance.

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]
like image 154
卢声远 Shengyuan Lu Avatar answered Sep 30 '22 13:09

卢声远 Shengyuan Lu


In each case, the values you are iterating with the each are map entries with a pointer to key and value. When you set it.value you are not replacing what is in the map. You are only updating the pointer in the map entry. To actually set the value, you will need to do the following:

m.findAll { it.value > 1 }.each { m[it.key] = 4 }
like image 22
Mike Clark Avatar answered Sep 30 '22 14:09

Mike Clark