groovy如何制作第二组和总和

时间:2016-01-24 18:42:19

标签: groovy

我在制作第二个->和做数学时遇到了麻烦:groupBytotaldifference只是正数的sum()和total只是负数的sum()。

这就是我得到的:

diffenrence

这就是我想要得到的:

[
    ["category":"Beer", "name":"Budweiser", "type":null, "price":50.00, "quantity":2],
    ["category":"Soft Drink", "name":"Pepsi", "type":null, "price":10.00, "quantity":5],
    ["category":"Soft Drink", "name":"Pepsi", "type":null, "price":10.00, "quantity":-5],
    ["category":"Soft Drink", "name":"Coke", "type":null, "price":10.00, "quantity":3],
    ["category":"Soft Drink", "name":"Pepsi", "type":null, "price":10.00, "quantity":7],
    ["category":"Alchool", "name":"Smir", "type":18, "price":5.00, "quantity":1],
    ["category":"Alchool", "name":"Smir", "type":18, "price":5.00, "quantity":-1],
    ["category":"Alchool", "name":"Bala", "type":20, "price":5.00, "quantity":5]
]

我正在尝试的代码:

[
    [Beer: [name: Budweiser, type: null, price: 50.00, total: 2, difference: 0] ],
    [SoftDrink: [name: Coke, type: null, price: 10.00, total: 3, difference: 0],
            [name: Pepsi, type: null, price: 10.00, total: 12, difference: 5] ],
    [Achool: [name:Smir, type:18, price: 5.00, total: 1, difference: 1],
            [name:Bala, type:20, price: 5.00, total: 5, difference: 0]]
]

1 个答案:

答案 0 :(得分:1)

试试这个:

products.groupBy { it.category }.collectEntries { category, product ->
  [(category): product.groupBy { it.name }.collect { name, p -> [
    name:name, 
    type: p[0].type, 
    price:p[0].price,
    total:p.quantity.sum { Math.max(0, it) },
    difference:p.quantity.sum { Math.max(0, -it)} 
  ]} ] 
 }​

注意:https://groovyconsole.appspot.com/script/5093590829105152

使用'double groupBy'(它不是更简单,因为你想重写嵌套数据):

products.groupBy({ it.category }, {it.name}).collectEntries { category, names ->
  [(category): names.collect { name, p -> [
    name:name, 
    type: p[0].type, 
    price:p[0].price,
    total:p.quantity.sum { Math.max(0, it) },
    difference:p.quantity.sum { Math.max(0, -it)}
  ] } ]
}