Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List as map value in grails

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

like image 735
xain Avatar asked Feb 25 '11 21:02

xain


2 Answers

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']
like image 80
Stefan Armbruster Avatar answered Oct 07 '22 18:10

Stefan Armbruster


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']]
like image 7
ataylor Avatar answered Oct 07 '22 18:10

ataylor