Home > Back-end >  Groovy iterating through Map of Maps
Groovy iterating through Map of Maps

Time:06-24

Let's say I have a Map:

Map exampleMap = ["person1": ["firstName": "John", "lastName": "Doe", "id": "1"], "person2": ["firstName": "Jane", "lastName": "Doe", "id": "2"]]

I want to iterate through this Map and print out the key and the values.

For example:

exampleMap.each{ item, key ->
    println item[key]
    println item["firstName"]
    println item["lastName"]

}

The sample output I want:

person1
John
Doe

The above approach gives me an error:

Caught: groovy.lang.MissingPropertyException: No such property: firstName for class: java.util.LinkedHashMap$Entry

I tried:

Map exampleMap = ["person1": ["firstName": "John", "lastName": "Doe", "id": "1"], "person2": ["firstName": "Jane", "lastName": "Doe", "id": "2"]] as ConfigObject
def props = exampleMap.toProperties()

But it would output key as a person1.firstName. Is it possible to output just person1?

Or what would be the best way to approach this?

CodePudding user response:

You mixed up the closure parameter order:

Map exampleMap = ["person1": ["firstName": "John", "lastName": "Doe", "id": "1"], "person2": ["firstName": "Jane", "lastName": "Doe", "id": "2"]]

exampleMap.each{ key, item ->
    println key
    println item["firstName"]
    println item["lastName"]
}

Try it in the Groovy Web Console.

  • Related