I’ve been working with Groovy for some time now and I think it’s one of the best languages for the JVM.
To show my love for this language I dedicate this weekend to showcase some of the enhancements Groovy has made to working with Lists, Maps and Collections. Some small tidbits – just for fun every few hours.
I’ll call it the Groovy Weekend Collections Showcase Reel!…ahem. In this first installment we’ll start with…
collate() is a method on any
Iterable to split or partition its elements into a sub-list of a certain size.
def names = ["Lassy", "Buttercup", "Carmella", "Moo-moo", "Cinnamon"] // collate into batches of 3 def collated = names.collate 3 assert collated == [['Lassy', 'Buttercup', 'Carmella'], ['Moo-moo', 'Cinnamon']]
You can even pass a 2nd parameter as the number of elements to step through for each sub-list.
collated = names.collate 3, 1 assert collated == [['Lassy', 'Buttercup', 'Carmella'], ['Buttercup', 'Carmella', 'Moo-moo'], ['Carmella', 'Moo-moo', 'Cinnamon'], ['Moo-moo', 'Cinnamon'], ['Cinnamon']]
There are many overloaded variants of
colate. Check out Groovy’s GDK documentation.