2017-03-06 48 views
0
  1. 在常規的組,我有maps.Each地圖的列表中包含3個鍵與 各自的值,如:如何形成相同值和鍵

    def group= [] as DataList 
    def groupRequiredMap = ["a": Metadata.groupName, 
             "b": Metadata.instance, 
             "c": Metadata.color] 
        group << groupRequiredMap 
    

    組的輸出被作爲如下::

    [[a:apple, b:0, c:red], 
    [a:apple, b:0, c:green], 
    [a:apple, b:0, c:blue], 
    [a:apple, b:1, c:brown], 
    [a:apple, b:1, c:violet], 
    [a:grapes, b:0, c:black], 
    [a:grapes, b:0, c:yellow], 
    [a:grapes, b:1, c:orange], 
    [a:grapes, b:1, c:pink]] 
    

欲形成一組與b = 0,一組用b = 1蘋果蘋果的,一組用b = 0葡萄和一組克用b強姦= 1等等。筆者想輸出是這樣的:

[[a:apple, b:0, c:[red, green, blue]], 
[a:apple, b:1, c:[brown,violet]], 
[a:grapes, b:0, c:[black,yellow]], 
[a:grapes, b:1, c:[orange,pink]] 
+1

你堅持了哪一點?你有一些不起作用的代碼嗎? –

回答

0

在這裏你去:

List list = [[a:'apple', b:0, c:'red'], [a:'apple', b:0, c:'green'], [a:'apple', b:0, c:'blue'], [a:'apple', b:1, c:'brown'], [a:'apple', b:1, c:'violet'], [a:'grapes', b:0, c:'black'], [a:'grapes', b:0, c:'yellow'], [a:'grapes', b:1, c:'orange'], [a:'grapes', b:1, c:'pink']] 

List result = []  

list.groupBy ({it.a},{it.b}).each { a -> 
    a.value.each { b -> 
     result << [a: a.key, b: b.key, c: b.value.c] 
    } 
} 

result 
+0

Thanks @Anton Hlinistry這正是我想要的,但是如果我們有4張地圖而不是3.will它會起作用嗎?像:def groupRequiredMap = [「a」:Metadata.groupName, 「b」:Metadata.instance, 「c」:Metadata.color,「d」:Metadata.required] –

+0

List list = [[a:'apple',b:0,c:'red',d:'required'],[a:'apple ',b:0,c:'green','required'],[a:'apple',b:0,c:'blue',d:「可選],[a:'apple',b:1 ,c:'brown',d:必須],[a:'apple',b:1,c:'violet',d:可選],[a:'葡萄',b:0,c:'黑色' ,d:'required'],[a:'grapes',b:0,c:'yellow',d:'optional'],[a:'葡萄',b:1,c:'orange',d :'required'],[a:'grapes',b:1,c:'pink',d:'optional']] –

+0

取決於你如何處理「d」。 –

0

代替each和變異的列表,你可以這樣做:

def list = [[a:'apple', b:0, c:'red'], 
       [a:'apple', b:0, c:'green'], 
       [a:'apple', b:0, c:'blue'], 
       [a:'apple', b:1, c:'brown'], 
       [a:'apple', b:1, c:'violet'], 
       [a:'grapes', b:0, c:'black'], 
       [a:'grapes', b:0, c:'yellow'], 
       [a:'grapes', b:1, c:'orange'], 
       [a:'grapes', b:1, c:'pink']] 

List result = list.groupBy({it.a}, {it.b}).collectMany { aValue, groupA -> 
    groupA.collect { bValue, values -> [a: aValue, b: bValue, c:values] } 
} 
0

groupBy是你想要的第一件事。因此,分組的關鍵是subMap("a","b") - 一張只包含原始地圖的「a」和「b」鍵的鍵/值的地圖。之後,通過傳播運算符*.將「關鍵地圖」與包含所有「c」的新地圖組合在一起。

list.groupBy{ it.subMap("a","b") }.collect{ k, ms -> k + [c: ms*.c] } 
相關問題