我有一个列表如下
ordersList=[[id:1, amount:1000, salesPerson:'XYZ'],
[id:2, amount:3000, salesPerson:'XYZ'],
[id:3, amount:1000, salesPerson:'ABC']
...n items
];
我想收集具有相同属性'salesPerson'的项目和'salesPerson'的所有订单金额的总和,最后我希望有如下列表,表示应为每个'salesPerson'创建一个列表这应该包含所有'salesPerson'
的订单最后,我期望的列表是
salesPersonOrdersList = [xyzSalesPersonOrdersList, abcSalesPersonOrdersList]
xyzSalesPersonOrdersList = [[name:'XYZ'], orders:[[id:1, amount:1000],[id:2, amount:3000]],[totalAmount:4000] ]
abcSalesPersonOrdersList = [[name:'ABC'], orders:[[id:3, amount:1000]],[totalAmount:1000] ]
如何做到这一点。
答案 0 :(得分:4)
使用groupBy
按名称对项目进行分组:
def ordersList=[[id:1, amount:1000, salesPerson:'XYZ'],
[id:2, amount:3000, salesPerson:'XYZ'],
[id:3, amount:1000, salesPerson:'ABC']
];
ordersList.groupBy{it.salesPerson}
//------------------------------------------------
//Result: [XYZ:[[id:1, amount:1000, salesPerson:XYZ], [id:2, amount:3000, salesPerson:XYZ]], ABC:[[id:3, amount:1000, salesPerson:ABC]]]
然后您可以转换地图以满足您的需求,如:
ordersList.groupBy{it.salesPerson}.collect{[name : it.key,orders : it.value]}
//-----------------------------------------------
//Result: [[name:XYZ, orders:[[id:1, amount:1000, salesPerson:XYZ], [id:2, amount:3000, salesPerson:XYZ]]], [name:ABC, orders:[[id:3, amount:1000, salesPerson:ABC]]]]