Hi all, my name is Hubert A. Klein Ikkink. Not a very common name, right? To make things easier I just picked the first letters of my firstname and surname and came up with haki. So there you have it, now I am also known as Mr. Haki or mrhaki for short. You can read more blog postings at www.mrhaki.com. I am a passionate Groovy and Java developer based in Tilburg, The Netherlands. My goal is to write clean, elegant, user-centered and high quality software. You can find me on Google+ and Twitter. Hubert is a DZone MVB and is not an employee of DZone and has posted 126 posts at DZone. You can read more from them at their website. View Full User Profile

Groovy Goodness: Collate a List into Sub-lists

04.14.2012
| 3847 views |
  • submit to reddit

I totally missed the new collate() method for List objects available since Groovy 1.8.6. With this method we can divide a list into sub-lists of a specified size. We can include a boolean parameter to indicate if we want to include remainders that don't fit in the specified size of the collated sub-lists. Finally we can use a parameter to define how many steps we go through the list before dividing the list into sub-lists.

 

def letters = 'a'..'g'

assert letters.collate(3) == [['a', 'b', 'c'], ['d', 'e', 'f'], ['g']]

// Step through original list with 
// 2 steps and collate.
assert letters.collate(3, 2) == [['a', 'b', 'c'], ['c', 'd', 'e'], ['e', 'f', 'g'], ['g']]

// Don't include remainder in result.
// Default a remainder is included in the result.
boolean remainder = false
assert letters.collate(3, remainder) == [['a', 'b', 'c'], ['d', 'e', 'f']]
assert letters.collate(3, 2, remainder) == [['a', 'b', 'c'], ['c', 'd', 'e'], ['e', 'f', 'g']]
Published at DZone with permission of Hubert Klein Ikkink, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)