在grails中列出为map值 [英] List as map value in grails

查看:142
本文介绍了在grails中列出为map值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要填写地图,以便:

I need to populate a Map so that:


  • 密钥是字符串

  • 该值是一个字符串列表

该过程是通过具有两个文本字段的表中的所有记录:参数和价值。 参数不是唯一的,有很多重复。所以我打算做的是:

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 
}

任何线索?

谢谢

推荐答案

通过使用Groovy 1.7中引入的withDefault,有一个简单的方法来实现这一点:

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

这篇关于在grails中列出为map值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆