Groovy / Grails:如何组合多个键组合?

时间:2015-02-10 05:58:32

标签: grails groovy functional-programming

我有一个列表,我想按所有三个键分组,我引用How to group a list of list

def given  = [
  [Country:'Japan',Flag:'Yes',Event:'New Year'],
  [Country:'china',Flag:'No',Event:'Spring Festival'],
  [Country:'uk',Flag:'No',Event:'National Holiday'],
  [Country:'us',Flag:'Yes',Event:'Labour Day'],
  [Country:'us',Flag:'Yes',Event:'New Year'],
  [Country:'uk',Flag:'Yes',Event:'Memorial Day']
]

我们可以分组:

 def mapped = given.groupBy {
      [(it["Country"]) : it["Flag"] ] }

如何按[(it["Country"]) : it["Flag"] : it["Event"] ]分组?

预期结果:[['Japan':['Yes':[NewYear]]]:[['Country':'Japan', 'Flag':'Yes', 'Event':'New Year']],..

2 个答案:

答案 0 :(得分:2)

given.groupBy( { it.Country }, { it.Flag }, { it.Event } )

以3个闭包为参数的方法。

答案 1 :(得分:2)

这有什么好处,我不明白。 @dmahapatro的解决方案提供了更易处理的结果。在您的示例中,您只想将递归映射作为组的键。我有最强烈的怀疑,这将很好地处理实际的分组案例。

def given  = [
[Country:'Japan',Flag:'Yes',Event:'New Year'],
[Country:'china',Flag:'No',Event:'Spring Festival'],
[Country:'uk',Flag:'No',Event:'National Holiday'],
[Country:'us',Flag:'Yes',Event:'Labour Day'],
[Country:'us',Flag:'Yes',Event:'New Year'],
[Country:'uk',Flag:'Yes',Event:'Memorial Day']
]

println given.groupBy{ [(it.Country): [(it.Flag): [it.Event]]] }.inspect()
//=> [['Japan':['Yes':['New Year']]]:[['Country':'Japan', 'Flag':'Yes', 'Event':'New Year']], ...