Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a list into equal sized lists in Groovy?

If I have this:

def array = [1,2,3,4,5,6] 

Is there some built-in which allows me to do this ( or something similar ):

array.split(2) 

and get:

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

?

like image 241
Geo Avatar asked May 27 '10 19:05

Geo


People also ask

How do I add one list to a list in Groovy?

Combine lists using the plus operator The plus operator will return a new list containing all the elements of the two lists while and the addAll method appends the elements of the second list to the end of the first one. Obviously, the output is the same as the one using addAll method.


1 Answers

EDIT As of groovy 1.8.6 you can use the collate method on lists

def origList = [1, 2, 3, 4, 5, 6, 7, 8, 9] assert [[1, 2, 3, 4], [5, 6, 7, 8], [9]] == origList.collate(4) 

Another method using inject and metaClasses

List.metaClass.partition = { size ->   def rslt = delegate.inject( [ [] ] ) { ret, elem ->     ( ret.last() << elem ).size() >= size ? ret << [] : ret   }   if( rslt.last()?.size() == 0 ) rslt.pop()   rslt }  def origList = [1, 2, 3, 4, 5, 6]  assert [ [1], [2], [3], [4], [5], [6] ] == origList.partition(1) assert [ [1, 2], [3, 4], [5, 6] ]       == origList.partition(2) assert [ [1, 2, 3], [4, 5, 6] ]         == origList.partition(3) assert [ [1, 2, 3, 4], [5, 6] ]         == origList.partition(4) assert [ [1, 2, 3, 4, 5], [6] ]         == origList.partition(5) assert [ [1, 2, 3, 4, 5, 6] ]           == origList.partition(6) assert [ ]                              == [ ].partition(2) 

Edit: fixed an issue with the empty list

like image 183
tim_yates Avatar answered Sep 20 '22 08:09

tim_yates