Hi I have complex structure
Map<Map<String,String>, Map<String,String>> a
And I want to iterate throught all its elements. I tried:
for(Map.Entry<Map<String,String>, Map<String,String>> first:firstMap.keySet()) {
...
}
And the error is
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 map?
1. Iterating over Map.entrySet() using For-Each loop : Map.entrySet() method returns a collection-view(Set<Map.Entry<K, V>>) of the mappings contained in this map. So we can iterate over key-value pair using getKey() and getValue() methods of Map.Entry<K, V>.
The first part to read is Map<String, String> This means "an instance of Map whose keys are String s and whose values are String s." For example, this might associate peoples' names with their driver's license numbers. We then use these as elements in a List<Map<String, String>>
The keySet()
returns only its keys, so it is a List of Map<String, String>
. If you want to iterate through its Map.Entry
, drop the .keySet()
:
for (Map.Entry<Map<String, String>, Map<String, String>> entry : firstMap) {
println "entry=$entry"
}
Other looping 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
}
You could just 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"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With