Groovy collate
collate groups consecutive list items into batches. Its keepRemainder argument controls whether an incomplete final batch is returned.
A simple example
collate
- Start with A, B, C
- Do this Split into groups of two
- Result [A, B] and [C]
Syntax
jobs.collate(batchSize, keepRemainder)
Run this example in Groovy
Save the program as Lesson.groovy. Use Groovy 4 on the JVM.
groovy Lesson.groovy
Split a work queue into fixed-size batches
A batch of items must be divided into pages, containers or work units of fixed size. Account for the final partial group so the last few items are neither lost nor counted as a full batch incorrectly.
def jobs = ['A', 'B', 'C', 'D', 'E']
println jobs.collate(2, true)
println jobs.collate(2, false)
[[A, B], [C, D], [E]] [[A, B], [C, D]]
Five jobs produce two pairs and one single-item batch. Dropping the tail is appropriate only when every emitted batch must be complete.
Groovy documentation for collate
Batch badge printing
A club sends seven names to a printer that takes three names per batch. Split the records into consecutive batches and retain a partial final batch. How many batches go to the desk?
Bundle class handouts
A classroom has eight sets of papers to bundle into fours. Split the records into consecutive batches and retain a partial final batch. How many batches go to the desk?