在Groovy中合并和聚合数据

时间:2015-11-12 12:50:05

标签: groovy group-by sum aggregate

我想知道聚合这些数据的最佳方法是什么?在Groovy中?

假设我有以下数据:

[
   [id: 1, name: bob, age:20, numberOfPackages: 10, numberOfPurchases:20 ],
   [id: 1, name: bob, age:20, numberOfPackages: 5, numberOfPurchases:6 ],
   [id: 2, name: Rob, age:22, numberOfPackages: 3, numberOfPurchases:5 ],
]

我希望将其转换为以下内容(合并 id / 名称 / 年龄,但总和价格 id 购买的数量

[
   [id: 1, name: bob, age:20, numberOfPackages: 15, numberOfPurchases:26 ],
   [id: 2, name: Rob, age:22, numberOfPackages: 3, numberOfPurchases:5 ],
]

2 个答案:

答案 0 :(得分:4)

单独总结价格和购买数量毫无意义,您的意思是:

def data = [
    [id: 1, name: 'bob', age:20, price: 10, numberOfPurchases:20],
    [id: 1, name: 'bob', age:20, price:  5, numberOfPurchases:6],
    [id: 2, name: 'rob', age:22, price:  3, numberOfPurchases:5]
]

data.groupBy { [id:it.id, name:it.name, age:it.age] }.collect { k, v ->
    [id:k.id,
     name:k.name,
     age:k.age,
     spend:v.collect { it.price * it.numberOfPurchases }.sum()]
}

给出了:

[
    [id:1, name:'bob', age:20, spend:230],
    [id:2, name:'rob', age:22, spend:15]
]

答案 1 :(得分:1)

可能是例如:

def data = [
    [id: 1, name: 'bob', age:20, price: 10, numberOfPurchases:20 ],
    [id: 1, name: 'bob', age:20, price: 5, numberOfPurchases:6 ],
    [id: 2, name: 'rob', age:22, price: 3, numberOfPurchases:5 ],
]

data.groupBy { it.id }.collectEntries { 
    [
        (it.key): [
            name: it.value.name.first(), 
            age: it.value.first(), 
            price: it.value.sum { it.price },
            numberOfPurchases: it.value.sum { it.numberOfPurchases },
        ]
    ] 
 }