Chris F
Chris F

Reputation: 16673

How to remove values in a Groovy map

Say I have this map

def map = [:]
map.put("us-east-1", ["vol-66c16ec2", "vol-654ce2c1", "vol-01234567"])
map.put("us-east-2", ["vol-12345678", "vol-87654321", "vol-abcdefgh"])

which results in...

{
  "us-east-1" : [
    "vol-66c16ec2", "vol-654ce2c1", "vol-01234567"
  ],
  "us-east-2" : [
    "vol-12345678", "vol-87654321", "vol-abcdefgh"
  ]
}

How can I iterate through the map so when value = "vol-abcdefgh" I want to remove that entry. So pseudo-code is...

for (it=iterate_through_map) {
  if (it == "vol-abcdefgh") {
     remove_entry(it)
  }
}

and the resulting map is now...

{
  "us-east-1" : [
    "vol-66c16ec2", "vol-654ce2c1", "vol-01234567"
  ],
  "us-east-2" : [
    "vol-12345678", "vol-87654321"
  ]
}

Upvotes: 0

Views: 5692

Answers (2)

Michael Easter
Michael Easter

Reputation: 24468

Consider the following (edit: updated with elegant improvement by dmahapatro):

def target = 'vol-abcdefgh'

def map2 = map.collectEntries { k, v -> [k, v - target] }

I have confirmed that it works in a Jenkins pipeline (unlike the spread operator, *).

Upvotes: 4

injecteer
injecteer

Reputation: 20699

Straight-forward would be something like

map.values()*.removeAll{ 'vol-abcdefgh' == it }

see docs for details on removeAll()

Upvotes: 0

Related Questions