Raju
Raju

Reputation: 143

Need to modify the list of Keys in a Groovy Map

I need to modify the key values from the given map below Example:

Map map= ["abcd":["name":"x", "age":"22"],"xyz":["name":"y", "age":"12"]]

Need to modify the key values and my final Map should be like below:

Map map= ["modifiedkey":["name":"x", "age":"22"],"someanotherkey":["name":"y", "age":"12"]] 

Upvotes: 1

Views: 3944

Answers (1)

Szymon Stepniak
Szymon Stepniak

Reputation: 42174

You can use collectEntries method from Groovy Collections API:

def defaultTransformation = { String key -> key }
def basicTransformation = { String key -> key.toUpperCase().reverse()
Map transformations = [abcd: basicTransformation, xyz: basicTransformation]

Map map= ["abcd":["name":"x", "age":"22"],"xyz":["name":"y", "age":"12"], "unchanged": ["name": "a", "age": "20"]]

Map newMap = map.collectEntries { [(transformations.getOrDefault(it.key, defaultTransformation).call(it.key)): it.value] }

In above example I use Closure that defines transformation - it expects single String parameter that is taken from current map entry key. As you can see Closure in Groovy is first class citizen, so we can pass it as e.g. a value in map. For this example I have created transformations map that defines mappings from old key to a new one. I have also created defaultTransformation closure - it will be used if mapping in transformations map for given key does not exist.

Running following script will produce newMap like this one:

[DCBA:[name:x, age:22], ZYX:[name:y, age:12], unchanged:[name:a, age:20]]

As you can see:

  • abcd key was transformed using basicTransformation closure
  • xyz key was also transformed using basicTransformation closure
  • unchanged key stayed the same, because there was no mapping in transformations map defined and the default one was used - a closure that returns key as is.

I hope it helps.

Upvotes: 2

Related Questions