groovy

In Groovy, how can I iterate through a list of maps and print each map's key/value?


I have the following test code where I create a list of Map<String,String> and want to print the key/value of each map in the list.

#!/usr/local/bin/groovy

List<Map<String,String>> list = []
Map<String, String> map1 = ["a":"a"]
list.add(map1)
println list
Map<String, String> map2 = ["b":"b"]
list.add(map2)
println list
list.each { m->
  println "${m.key} ${m.value}"
}

When executing the code, I get

[[a:a]]
[[a:a], [b:b]]
null null
null null

What is the correct way to print each map's key and value in the list?


Solution

  • you have list of maps. so, you need to iterate each map as well:

    List<Map<String,String>> list = []
    Map<String, String> map1 = ["a":"a"]
    list.add(map1)
    println list
    Map<String, String> map2 = ["b":"b"]
    list.add(map2)
    println list
    list.each { map ->
      map.each{ entry ->
        println "${entry.key} ${entry.value}"
      }
    }