使用HQL查询我已经能够生成以下映射,其中键表示java.util.Calendar中定义的月号常量,并且每个值都是映射:
[
0:[ client_a:[order1, order2, order3]],
1:[ client_b:[order4], client_c:[order5, order6], client_d:[order7]],
2:[ client_e:[order8, order9], client_f:[order10]]
]
order1,order2,...是名为Order的域类的实例:
class Order {
String description
Date d
int quantity
}
现在我有了包含属于某个特定年份的订单的结构,但我并不关心Order对象本身。我只想要每月所有订单数量的总和。所以结构看起来应该是这样的:
[
0:[ client_a:[321]],
1:[ client_b:[9808], client_c:[516], client_d:[20]],
2:[ client_e:[22], client_f:[10065]]
]
我不介意这些值是否是一个元素的列表或根本没有列表。如果可以的话,无论如何都会没问题:
[
0:[ client_a:321 ],
1:[ client_b:9808, client_c:516, client_d:20 ],
2:[ client_e:22, client_f:10065 ]
]
我知道我必须在每个订单列表中应用.sum{it.quantity}
之类的东西来获得我想要的结果,但我不知道如何迭代它们,因为它们嵌套在另一个地图中。
谢谢。
答案 0 :(得分:3)
你走了:
class Order {
String description
Date d
int quantity
}
def orders = [
0:[ client_a:[new Order(quantity:1), new Order(quantity:2), new Order(quantity:3)]],
1:[ client_b:[new Order(quantity:4)], client_c:[new Order(quantity:5), new Order(quantity:6)], client_d:[new Order(quantity:7)]],
2:[ client_e:[new Order(quantity:8), new Order(quantity:9)], client_f:[new Order(quantity:10)]]
]
def count = orders.collectEntries { k, v ->
def nv = v.collectEntries { nk, nv ->
[(nk): nv*.quantity.sum()]
}
[(k):(nv)]
}
assert count == [0:[client_a:6], 1:[client_b:4, client_c:11, client_d:7],2:[client_e:17, client_f:10]]
答案 1 :(得分:2)
def map = [
0:[ client_a:[[q: 23], [q: 28], [q: 27]]],
1:[ client_b:[[q: 50]], client_c:[[q: 100], [q: 58]], client_d:[[q: 90]]],
2:[ client_e:[[q: 48], [q: 60]], client_f:[[q: 72]]]
]
map.collectEntries { k, v ->
[ k, v.collectEntries { key, val ->
[ key, val*.q.sum() ]
} ]
}
您也可以使用val.sum { it.q }
代替val*.q.sum()