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]]
?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With