groovy groupby 多个字段

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

最佳答案

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

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

关于groovy groupby 多个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40100943/

相关文章:

两张表的 MySQL 并集,一张带有时间戳,一张带有日期

list - 如何获取我在 groovy 中迭代的列表的引用

java - 我应该在测试期间模拟 Spring Cloud Config 服务器属性吗?

r - 使用 group_by 和列条件在数据框中查找值

python - 如何使用 python3 在 "horizontal union"中加入两个 pandas DataFrame

mysql对一张表中的多行进行分组

java - 字符串到日期转换的问题

dictionary - 我怎样才能在groovy中进行有条件的collectEntries

groovy - Groovy 类中的 static {} 有什么意义?

SQL SELECT with GROUP BY,返回到组