Split collection into sub collections in Groovy

前端 未结 3 1804
轮回少年
轮回少年 2021-01-14 05:34

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

3条回答
  •  别那么骄傲
    2021-01-14 06:15

    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

提交回复
热议问题