在groovy中,我有一个地图列表。每个地图包含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]]
答案 0 :(得分: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
答案 1 :(得分: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] }
}
答案 2 :(得分:0)
groupBy
是你想要的第一件事。因此,分组的关键是subMap("a","b")
- 一张地图,它只包含原始地图的“a”和“b”键的键/值。之后,您通过展开运算符*.
将“关键地图”与包含所有“c”的新地图合并。
list.groupBy{ it.subMap("a","b") }.collect{ k, ms -> k + [c: ms*.c] }