groovy groupby多场

时间:2016-10-18 06:23:16

标签: groovy group-by

我有一个列表:

def given  = [
            [Country:'Japan',Flag:'Yes',Event:'New Year', Amount:70],
            [Country:'china',Flag:'No',Event:'Spring Festival', Amount:60],
            [Country:'us',Flag:'Yes',Event:'Labour Day', Amount:10],
            [Country:'us',Flag:'Yes',Event:'Labour Day', Amount:20]
    ]

我的期望是:

[
        [Country:'Japan',Flag:'Yes',Event:'New Year', Amount:70],
        [Country:'china',Flag:'No',Event:'Spring Festival', Amount:60],
        [Country:'us',Flag:'Yes',Event:'Labour Day', Amount:30]
]

2 个答案:

答案 0 :(得分:4)

另一种可能性(但结果完全相同)

given.groupBy { it.subMap('Country', 'Flag', 'Event') }
     .collect { k, v -> k + [Amount: v.Amount.sum()] }

答案 1 :(得分:3)

我终于做到了

def result = given.groupBy { [Country:it.Country, Flag:it.Flag, Event:it.Event] }.collect { k, v ->
    [Country:k.Country,
     Flag:k.Flag,
     Event:k.Event,
     Amout:v.collect { it.Amount }.sum()]
}
相关问题