Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

loops

map

groovy

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?

like image 712
Xelian Avatar asked Dec 02 '13 15:12

Xelian


People also ask

How do I iterate a String object on a 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>.

What is string string map?

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


2 Answers

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
}
like image 106
Will Avatar answered Sep 29 '22 19:09

Will


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"
}
like image 22
tim_yates Avatar answered Sep 29 '22 19:09

tim_yates