将收藏拆分为Groovy中的子集合 [英] Split collection into sub collections in Groovy
问题描述
我有一个包含未知数量项目的数组,我想将其分解为单独的数组,以便每个单独的数组包含不超过4个项目。在Groovy中执行此操作的最佳方式是什么?感谢!
我想出了这个: 这应该给你: 使用Groovy 1.8.6+,您可以使用 I have an array containing an unknown number of items that I would like to split into separate arrays so that each separate array contains no more than 4 items. What is the best way to do this in Groovy? Thanks! We had this here: How to split a list into equal sized lists in Groovy? I came up with this: Which should give you:
With Groovy 1.8.6+ you can use 这篇关于将收藏拆分为Groovy中的子集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
List.metaClass.partition = {size - >
def rslt = delegate.inject([[]]){ret,elem - >
(ret.last()<<< elem).size()> =大小? ret<< []:ret
}
!rslt.last()? rslt [0 ..- 2]:rslt
}
def list = [1,2,3,4,5,6] .partition(4)
[[1,2,3,4],[5,6]]
更新!
list.collate(4)
来获得相同的结果 p> List.metaClass.partition = { size ->
def rslt = delegate.inject( [ [] ] ) { ret, elem ->
( ret.last() << elem ).size() >= size ? ret << [] : ret
}
!rslt.last() ? rslt[ 0..-2 ] : rslt
}
def list = [1, 2, 3, 4, 5, 6].partition( 4 )
[ [ 1, 2, 3, 4 ], [ 5, 6 ] ]
Update!
list.collate( 4 )
to get the same result