I need to modify map elements while iterating a map, in my case subtract some elements (list). Like this:
def a = [
1: [1, 2, 3],
2: [3, 2, 4],
3: [3, 2, 4],
4: [5, 2, 1],
]
def b = [3]
println a
a.values().each{ tr ->
tr = tr - b
}
println a
The a
map has not changed. Result is:
[1:[1, 2, 3], 2:[3, 2, 4], 3:[5, 3, 1], 4:[5, 2, 1]]
[1:[1, 2, 3], 2:[3, 2, 4], 3:[5, 3, 1], 4:[5, 2, 1]]
However, I want the result to be [1:[1, 2], 2:[2, 4], 3:[5, 1], 4:[5, 2, 1]]
. What I am doing wrong? Due to the fact that the initial map is rather big I do not want to construct another map with less elements (result map).
work directly on the map instead:
a.keySet().each{
a[it]-=b
}
In your code you are assigning the result to the local variable.
If you have concerns about the amount of changes you might look into use of removeAll()
or by iterating over b
and remove()
each one. Those change the list in place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With