【问题标题】:groovy groupby multiple fieldgroovy groupby 多个字段
【发布时间】:2016-10-18 06:23:16
【问题描述】:

我有一个类似的列表:

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

【问题讨论】:

    标签: groovy group-by


    【解决方案1】:

    我终于成功了

    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()]
    }
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-23
        • 2018-06-29
        • 2018-06-20
        相关资源
        最近更新 更多