Parse Map

I have a map of the form:
[1:[var:1234, item:abcd], 2:[var:5678, item:efgh]]

How do I parse the individual items in an app? Can't seem to figure it out myself.

Something like this?

map = [1:[var:1234, item:abcd], 2:[var:5678, item:efgh]]
map.each{
    thisIterationNumber = it.key
    thisVar = it.value.var
    thisItem = it.value.item

    // Do your stuff
}

This is a map of maps. Let's assume the following:

Map outerMap = [1:[var:1234, item:abcd], 2:[var:5678, item:efgh]]
outerMap[1] = [var:1234, item:abcd]
outerMap[2] = [var:5678, item:efgh]

Now, it might be:

outerMap['1'] = [var:1234, item:abcd]
outerMap['2'] = [var:5678, item:efgh]

Depending on whether it's an Integer 1 or the string representation "1".

With Groovy, you can also iterate with the each or eachWithIndex closures, like this:

outerMap.each{ k,v -> doSomething(k,v) }

which with this example would do the following:

doSomething(1234, abcd)
doSomething(5678, efgh)

That worked. One more question, in the each iteration, is there a way to extract the iteration number? Ie the 1 or 2, etc. What I want to do is find the highest map used.

I edited my example above.
The it.key statement will contain the key of the map iteration.

I tried that, but the β€˜it’ gives me the entire map entry for a given number. I need to extract just the array position.

1={var=1234, item=abcd} is what I get for each array position

Sorry. Brain fart moment. I again edited my answer above.
The correct usage is it.key.

1 Like

Instead of each{} use eachWithIndex{}.

Example:
each{runMethod(it)}
eachWithIndex(runMethod(it, index)}

each{} has it as the implicit name for the current iteration object, eachWithIndex{} uses it and index

Alternatively, you can specify names:
eachWithIndex{ myThing, myIndex -> doStuff(myThing, myIndex)}

3 Likes