Input >> list = [[1,2,3], [6], [3,4,5,6]]
Output >> [1,2,3,3,4,5,6,6]
Run Code Online (Sandbox Code Playgroud)
我想知道是否有比这更简单的事情
l = []
list.each{ l = l + it }
println l
Run Code Online (Sandbox Code Playgroud)
像默认的groovy闭包或方法?
tim*_*tes 77
试试flatten
,即:
list.flatten()
Run Code Online (Sandbox Code Playgroud)
或者,获得您想要的输出:
list = [[1,2,3], [6], [3,4,5,6]]
assert list.flatten().sort() == [1,2,3,3,4,5,6,6]
Run Code Online (Sandbox Code Playgroud)
由于有些人可能会错过@Desty 的评论,在此作为答案发布:
请注意,其语义有所不同,因为它通过列表进行递归,在如下情况下产生不同的结果:[[1,2,3], [4,[5]],[6]].flatten()。进行 OP 串联的最简洁方法是 list.collectMany { it }
例子:
list = [[1,2,3], [6], [3,4,5,6]]
assert list.collectMany{ it }.sort() == [1,2,3,3,4,5,6,6]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
23577 次 |
最近记录: |