Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get key in groovy maps

Tags:

maps

groovy

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 
like image 875
kumar Avatar asked Feb 04 '11 12:02

kumar


People also ask

How do I iterate a map in Groovy?

If you wanted to do it that way, iterate over map. keySet() and the rest will work as you expected. It should work if you use s. key & s.

How do I use Groovy maps?

Maps are generally used for storing key-value pairs in programming languages. You have two options to declare a map in groovy. First option is, define an empty map and put key-value pairs after. Second option is declaring map with default values.

What is LazyMap in Groovy?

public class LazyMap extends AbstractMap<String,Object> This maps only builds once you ask for a key for the first time. It is designed to not incur the overhead of creating a map unless needed.


2 Answers

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.

like image 137
Sean Patrick Floyd Avatar answered Oct 22 '22 14:10

Sean Patrick Floyd


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

In groovy * is use for iterate all

like image 34
Om Prakash Avatar answered Oct 22 '22 13:10

Om Prakash