Iterate over Map <Map <String, String>, Map <String, String >> in groovy

Hi i have a complicated structure

 Map<Map<String,String>, Map<String,String>> a

And I want to repeat all its elements. I tried:

for(Map.Entry<Map<String,String>, Map<String,String>> first:firstMap.keySet()) { 
...
}

And mistake

Cannot cast object '{key1=value1, key2=value2, key3=value3, key4=value4}' with class 'java.util.LinkedHashMap' to class 'java.util.Map$Entry' due to: groovy.lang.GroovyRuntimeException: Could not find matching constructor for: java.util.Map$Entry(java.util.LinkedHashMap)

How to iterate over my card?

+4
source share
2 answers

You can simply use each:

def a = [ ([a:'tim',b:'xelian']):[ a:1,b:2 ],
          ([a:'alice',b:'zoe']):[ a:3,b:4 ] ]

a.each { key, value ->
    println "Key $key == Value $value"
}
+2
source

keySet()returns only its keys, so this is a list Map<String, String>. If you want to iterate through Map.Entry, release .keySet():

for (Map.Entry<Map<String, String>, Map<String, String>> entry : firstMap) {
  println "entry=$entry"
}

Other cycling options:

// iterate with two arguments
firstMap.each { Map<String, String> key, Map<String, String> value ->
  println "key=$key, value=$value"
}

// iterate through entries
firstMap.each { Map.Entry<Map<String, String>, Map<String, String>> entry ->
  println "entry=$entry"
}

// untyped
for (entry in firstMap) {
  println entry
}
+4
source

All Articles