开发者

Split collection into sub collections in Groovy

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 开发者_如何学Pythonitems. 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:

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 )

Which should give you:

[ [ 1, 2, 3, 4 ], [ 5, 6 ] ]

Update!

With Groovy 1.8.6+ you can use list.collate( 4 ) to get the same result


Answer by tim_yates is cool, but it throws java.lang.ArrayIndexOutOfBoundsException on empty lists (for example: [].partition(4)). This can be fixed in this way:

List.metaClass.partition = {size ->
    if (!delegate)
        return []

    def rslt = delegate.inject([[]]) {ret, elem ->
        (ret.last() << elem).size() >= size ? (ret << []) : ret
    }
    !rslt.last() ? rslt[0..-2] : rslt
}

assert [].partition(4) == []
assert [1, 2, 3, 4, 5, 6].partition(4) == [[1, 2, 3, 4], [5, 6]]


Since Groovy 1.8.6, you can use collate:

def letters = 'a'..'g'
assert letters.collate(3) == [['a', 'b', 'c'], ['d', 'e', 'f'], ['g']]

def letters = 'a'..'g'
assert letters.collate(3) == [['a', 'b', 'c'], ['d', 'e', 'f'], ['g']]

Credit to Mrhaki's Groovy goodness series: http://mrhaki.blogspot.com.au/2012/04/groovy-goodness-collate-list-into-sub.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜