Split an iterable into fixed-size Groovy batches
Groovy
List<List> chunk(Iterable source, int size) {
if (size < 1) throw new IllegalArgumentException('size must be >= 1')
List<List> batches = []
List current = []
for (item in source) {
current << item
if (current.size() == size) {
batches << current
current = []
}
}
if (current) batches << current
batches
}
println chunk(1..7, 3)