Process a Collection a batch at a time (groovy)
daniel Wed, 04/10/2013 - 10:15am
This snippet will allow you to process a collection in "batches". In other words, grab the next n records and pass them to a function.
def vals = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']
//
batches(vals, 3){ batch, batchNumber ->
println "batch $batchNumber: $batch"
}
//
public void batches(Collection vals, int batchSize, Closure action){
Collection batch
int batchNumber = 0
for(int i = 0; i < vals.size(); i = i+batchSize){
batch = []
(i..(i+batchSize-1)).each{
if(it< vals.size()){
batch << vals[it]
}
}
action.call(batch, batchNumber++)
}
}
- Log in to post comments