我想按3个属性进行分组,但不是每个属性都是它自己的嵌套数组。我想要的是什么:
def values=[
[day:1,month:1,year:1],
[day:1,month:1,year:1],
[day:2,month:1,year:1],
[day:2,month:2,year:1]
];
/*...some code to group by DAY, MONTH, AND YEAR
..desired result is that items with the same day,
month, and year end up in a one level deep subarray
*/
[
[[day:1,month:1,year:1],[day:1,month:1,year:1]],
[[day:2,month:1,year:1]] ,
[[day:2,month:2,year:1]]
];
使用带有多个闭包的 groupBy()方法,我将每个分组属性作为自己的嵌套数组,如[year [month [day []]]],这是不是什么我需要。
答案 0 :(得分:2)
您希望采用groupBy函数来执行您需要的操作。在此示例中,您的地图已经存在您要将其分组的身份。所以这足以满足您的需求:
Swift_TransportException in StreamBuffer.php line 269: Connection could not be established with host mailtrap.io [Connection refused #111]
如果您确实在地图中有更多值,则可以使用def values=[
[day:1,month:1,year:1],
[day:1,month:1,year:1],
[day:2,month:1,year:1],
[day:2,month:2,year:1],
]
// just the identity
println values.groupBy().values()
// => [[[day:1, month:1, year:1], [day:1, month:1, year:1]], [[day:2, month:1, year:1]], [[day:2, month:2, year:1]]]
分组到一个级别:
subMap
在挑剔的一面:那些是你得到的嵌套地图。
答案 1 :(得分:1)
考虑以下使用inject
来构建一个映射,其键是适当的组,值是所需的列表:
(修改:更新地图密钥的构造,每条评论)
def values=[
[day:1,month:1,year:1],
[day:1,month:1,year:1],
[day:2,month:1,year:1],
[day:2,month:2,year:1]
];
def groupMap = [:].withDefault{ key -> [] }
def result = values.inject(groupMap) { val, m ->
val["${m.'day'}:${m.'month'}:${m.'year'}"] << m
val
}.values()
assert [[day:1, month:1, year:1], [day:1, month:1, year:1]] == result[0]
assert [[day:2, month:1, year:1]] == result[1]
assert [[day:2, month:2, year:1]] == result[2]