groovy groupby多字段

Jun*_* Li 0 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]
    ]
Run Code Online (Sandbox Code Playgroud)

我期望会是这样的:

[
        [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]
]
Run Code Online (Sandbox Code Playgroud)

Jun*_* Li 5

我终于做到了

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()]
}
Run Code Online (Sandbox Code Playgroud)


tim*_*tes 5

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

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