BowerStudios.com

  • My Lab
  • Family
  • Friends
  • Professional
  • About
Home

Process a Collection a batch at a time (groovy)

daniel —Wed, 04/10/2013 - 10:15am

  • Groovy

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

Navigation

  • Search
  • Recent content
  • Contact Me
  • Mail
  • Pass Hasher
  • Bower Studios Admin

Quotes

daniel —Fri, 07/01/2011 - 12:51pm

When someone says, "I want a programming language in which I need only say what I want done," give him a lollipop.

—

Alan Perlis

  • Log in to post comments
  • daniel's quotes

Popular content

Last viewed:

  • Recovering from an Out of Memory error on Java
  • Using SSL with an IP address instead of DNS
  • how-do-i-search-for-elements-whose-collection-contains-another-element-in-grails
  • Solr Transactions
  • Starting Apache Tomcat in debug mode on Windows

Copyright 2021 Daniel Bower
  • My Lab
  • Family
  • Friends
  • Professional
  • About