Maps and submap


I'm new to groovy and I need to show in a combo box some values for setting up the language for my app. The current structure looks like this:

def countries = ["Bulgarian": ["Bulgaria": "bg-BG"],
"Chinese (Simplified)": ["China": "zh-CN", "Hong Kong": "zh-HK", "Taiwan, Province of China": "zh-TW"],
"Dutch": ["Belgium": "nl-BE", "Netherlands": "nl-NL"]]

I'd like to show this in my combo box:
Bulgarian - Bulgaria (bg-BG)
Chinese (Simplified) - China (zh-CN)
Chinese (Simplified) - Hong Kong (zh-HK)
Chinese (Simplified) - Taiwan, Province of China (zh-TW)
Dutch - Belgium(nl-BE)
Dutch - Netherlands(nl-NL)

My code looks like this but it's wrong:

def countriesList = [:]
countries.each { countriesList << [${it.key}: it.value]}

Anyone has an idea how I can get it right?

That should be

|countries.each { countriesList << ["${it.key}": it.value]}|

for starters, but it.value is a Map, and it looks like you actually want a list in the final result.

1 Like

Thanks! I was able to do it by using this method:

def flattenMap(Map map) {    
    def flattened = [:]
    map.collectEntries { k, v -> 
        if (v instanceof Map) {
          flattenMap(v).collectEntries {  k1, v1 -> 
                 flattened << [ "${v1}": "${k} - ${k1} (${v1})" ]  
        } else {
            flattened << [ "${k}": v ]  
    return flattened

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.