如何动态创建地图?

时间:2013-11-27 19:36:58

标签: map groovy

我有点卡在这里,直接创建像这样的地图

def map = [[group="group1",member="groover"],
           [group="group1",member="jason"],
           [group="group2",member="groover"],
           [group="group2",member="jason"]
]

迭代它并打印..

map.each{
    println it
}

..(所需)输出:

[group1, groover]
[group1, jason]
[group2, groover]
[group2, jason]

现在,如何动态创建类似的地图?

def dynamicMap = [:]

    for(int i=1;i<3;i++){  // This is not working particulary well...
        dynamicMap.group= "group$i"
        dynamicMap.member= "groover"
        dynamicMap.member= "jason"
    }

dynamicMap.each{
    println it
}

(INCORRECT)OUTPUT

group=group2
member=jason

3 个答案:

答案 0 :(得分:3)

这是地图列表,而不是地图,但是:

def dynamicMap = (1..2).collectMany { n ->
    [ [ group:"group$n", member:'groover' ],
      [ group:"group$n", member:'jason' ] ]
}

答案 1 :(得分:2)

首先,你的地图不是真正的地图。这是一张地图清单。

您正在寻找的解决方案是

def dynamicMap = []
for(int i=1;i<3;i++){ 
    dynamicMap << [group: "group$i", member: "groover"]
    dynamicMap << [group: "group$i", member: "jason"]
}

答案 2 :(得分:0)

警告,combinations()仅适用于2.2.0+,我相信。最后的2.2.0示例。 (我还不清楚你是否想要一份地图列表或一份清单。)

def groups = [ "group1", "group2"]
def members = [ "groover", "jason" ]
def list = [groups, members].combinations { g, m -> ["group": g, "member": m] }
list.each { println it }

// Gives:
//[group:group1, member:groover]
//[group:group2, member:groover]
//[group:group1, member:jason]
//[group:group2, member:jason]

// OR
list = [groups, members].combinations { g, m -> [g, m] }
list.each { println it }

// Gives:
//[group1, groover]
//[group2, groover]
//[group1, jason]
//[group2, jason]

// But if you don't actually need the resulting list of lists
// (i.e. you just want to process the combinations)
[groups, members].eachCombination { println it }

// Gives:
//[group1, groover]
//[group2, groover]
//[group1, jason]
//[group2, jason]

// OR (Should work pre-2.2.0+)
list = []
groups.each { g ->
   members.each { m -> list << [g, m] /* or ["group": g, "member": m] */ }
}
list.each { println it }

// Gives:
//[group1, groover]
//[group2, groover]
//[group1, jason]
//[group2, jason]