将具有相同键的映射列表合并到一个条目但与其他字段不同

时间:2015-09-18 07:58:45

标签: groovy

我需要一些帮助来转换我当前的列表:

List data = [
    [name: "product1", category: "tshirt", color: "white", hex: "ffffff"],
    [name: "product1", category: "tshirt", color: "black", hex: "000000"],
    [name: "product2", category: "shoes", color: "white", hex: "ffffff"],
    [name: "product2", category: "shoes", color: "black", hex: "000000"],
]

对此:

List convertedData = [
    [name: "product1", category: "tshirt", colors: [ [color: "white", hex: "fffff"], [color: "black", hex: "000000"] ]],
    [name: "product2", category: "shoes", colors: [ [color: "white", hex: "fffff"], [color: "black", hex: "000000"] ]]
]

我确实尝试过使用groupBy,但没有成功实现上面相同的输出,并且已经有很多循环,这不是一个好习惯。

1 个答案:

答案 0 :(得分:0)

使用groupBy并不是一个坏主意。您可以按名称和类别进行分组,然后收集组。 E.g:

def data = [[name: "product1", category: "tshirt", color: "white", hex: "ffffff"],
     [name: "product1", category: "tshirt", color: "black", hex: "000000"],
     [name: "product2", category: "shoes", color: "white", hex: "ffffff"],
     [name: "product2", category: "shoes", color: "black", hex: "000000"],]

println data.groupBy{
    it.subMap(["name","category"])
}.collect{
    it.key + [colors: it.value*.subMap(["color","hex"])]}

// [[name:product1, category:tshirt, colors:[
//  [color:white, hex:ffffff], [color:black, hex:000000]]], 
// [name:product2, category:shoes, colors:[
//  [color:white, hex:ffffff], [color:black, hex:000000]]]]