迭代Map <map <string,string>,Map <string,string>&gt; in groovy </string,string> </map <string,string>

时间:2013-12-02 15:49:52

标签: loops map groovy

你好我有复杂的结构

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

我想迭代其所有元素。我试过了:

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

错误是

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)

如何迭代我的地图?

2 个答案:

答案 0 :(得分:4)

keySet()仅返回其键,因此它是Map<String, String>的列表。如果您要遍历其Map.Entry,请删除.keySet()

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

其他循环选项:

// 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
}

答案 1 :(得分:3)

您可以使用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"
}