Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy modify map elements while iterating a map

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).

like image 545
Bob Avatar asked Sep 19 '25 12:09

Bob


1 Answers

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.

like image 128
cfrick Avatar answered Sep 21 '25 06:09

cfrick