List as map value in grails

12,313

Solution 1

There is a IMHO little bit simpler way doing this by using 'withDefault' introduced in Groovy 1.7:

all = [
    [parameter: 'foo', value: 'aaa'],
    [parameter: 'foo', value: 'bbb'],
    [parameter: 'bar', value: 'ccc'],
    [parameter: 'baz', value: 'ddd']
]

def myMap = [:].withDefault { [] }
all.each {
    myMap[it.parameter] << it.value
}

assert myMap.size() == 3
assert myMap.foo == ['aaa','bbb']
assert myMap.bar == ['ccc']
assert myMap.baz == ['ddd']

Solution 2

You can use the Map.groupBy method, which will split the collection into a map of groups based on the passed in closure. Here's a full example, which also calls collect to make each parameter point to just the values:

all = [
    [parameter: 'foo', value: 'aaa'],
    [parameter: 'foo', value: 'bbb'],
    [parameter: 'bar', value: 'ccc'],
    [parameter: 'baz', value: 'ddd']
]
tmpMap = all.groupBy{it.parameter}
myMap = [:].putAll(tmpMap.collect{k, v -> [k, v.value] as MapEntry})

assert myMap == [foo: ['aaa', 'bbb'], bar: ['ccc'], baz:['ddd']]
Share:
12,313
xain
Author by

xain

SW PM,architect and programmer

Updated on June 09, 2022

Comments

  • xain
    xain almost 2 years

    I need to populate a Map so that:

    • The Key is a String
    • The Value is a List of Strings

    The process is to go through all the records in a table that has two text fields : "parameter" and "value". "Parameter" is not unique an has many duplicates. So what I intent to do is:

    def all = MyTable.findAll()
    def mymap = [:]
    
    all.each {
      // add to mymap the element "it.value" to the list that has "it.parameter" as key 
    }
    

    Any clues ?

    Thanks