java - 如何在 groovy 中收集列表的相似项目

标签 java list grails collections groovy

我有一个列表如下

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

如何做到这一点。

最佳答案

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

然后您可以转换 map 以满足您的需要,例如:

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

关于java - 如何在 groovy 中收集列表的相似项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20966804/

相关文章:

grails - 服务层和交易

python - 从列表列表构建字典并维护元素的位置

java gwt multiselectionmodel禁用蓝色

java - 如何在主 Activity 的for循环内的线程内生成TextView

java - URL 编码对我的字符串进行两次编码

html - 动态垂直多列列表在 IE 中不起作用

c - 填充链表的函数,但适用于 n 个列表类型

grails - Grails 中的 HTTPBuilder 编码 utf-8

tomcat - Grails 不在 Tomcat 环境中编译

java - Orient DB - 使用JAVA导出指定类的子类