Get key in groovy maps

GroovyMaps

Groovy Problem Overview


def map = [name:"Gromit", likes:"cheese", id:1234]

I would like to access map in such a way that I can get the key

something like the output should be

map.keys returns array of string. basically i just want to get the keys

output:

name
likes
id

Groovy Solutions


Solution 1 - Groovy

try map.keySet()

and if you want an array:

map.keySet() as String[]; // thx @tim_yates

Or, more groovy-ish:

map.each{
    key, value -> print key;
}

Warning: In Jenkins, the groovy-ish example is subtly broken, as it depends on an iterator. Iterators aren't safe in Jenkins Pipeline code unless wrapped in a @NonCPS function.

Solution 2 - Groovy

def map = [name:"Gromit", likes:"cheese", id:1234]
    
println map*.key

> In groovy * is use for iterate all

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkumarView Question on Stackoverflow
Solution 1 - GroovySean Patrick FloydView Answer on Stackoverflow
Solution 2 - GroovyOm PrakashView Answer on Stackoverflow