Skip to content

Instantly share code, notes, and snippets.

@xlson
Created June 15, 2011 12:48
Show Gist options
  • Save xlson/1027008 to your computer and use it in GitHub Desktop.
Save xlson/1027008 to your computer and use it in GitHub Desktop.
Adds method that will batch the values in a list into a new list containing batches of items
Object.metaClass.partition = { partitionSize ->
def result = delegate.inject([[]]) { partitioned, it ->
if(partitioned.last().size() == partitionSize) {
partitioned << [it]
} else {
partitioned.last() << it
}
partitioned
}
result?.last().size() == 0 ? [] : result
}
assert [1, 2, 3, 4, 5].partition(1) == [[1], [2], [3], [4], [5]]
assert [1, 2, 3].partition(2) == [[1, 2], [3]]
assert [1, 2, 3].partition(5) == [[1, 2, 3]]
assert [].partition(100) == []
@timyates
Copy link

I like that this gives you an easy to read way to map a list, ie;

assert [ a:10, b:20, c:30 ] == [ 'a', 10, 'b', 20, 'c', 30 ].partition( 2 ).collectEntries { it }

@xlson
Copy link
Author

xlson commented Jun 15, 2011

Nice, I hadn't even thought of that. My use case is for creating batches of data to be sent into a remote service. Partition that was used on the stackoverflow page is probably a name that is more in line with what it actually does.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment