gpt4 book ai didi

grails - Groovy中的分组和总和收集

转载 作者:行者123 更新时间:2023-12-02 13:52:35 25 4
gpt4 key购买 nike

我有一个对象集合,我想按月份,名称和总数进行分组:

def things = [
[id:1, name:"fred", total:10, date: "2012-01-01"],
[id:2, name:"fred", total:10, date: "2012-01-03"],
[id:3, name:"jane", total:10, date: "2012-01-04"],
[id:4, name:"fred", total:10, date: "2012-02-11"],
[id:5, name:"jane", total:10, date: "2012-01-01"],
[id:6, name:"ted", total:10, date: "2012-03-21"],
[id:7, name:"ted", total:10, date: "2012-02-09"]
];

我希望输出为:
[
"fred":[[total:20, month:"January"],[total:10, month:"February"]],
"jane":[[total:20,month:"January"]],
"ted" :[[total:10, month:"February"],[total:10, month:"March"]]
]

或类似的规定。使用groovy / grails实现此目的的最佳方法是什么?

最佳答案

以下几行

things.inject([:].withDefault { [:].withDefault { 0 } } ) { 
map, v -> map[v.name][Date.parse('yyyy-MM-dd', v.date).format('MMMM')] += v.total; map
}

将为您提供以下结果:
[fred:[January:20, February:10], jane:[January:20], ted:[March:10, February:10]]

(适用于Groovy> = 1.8.7和2.0)

关于grails - Groovy中的分组和总和收集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13296325/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com