What’s new in Groovy 1.8.6: The collate method

I’m going to take a look at some of the new functions in Groovy 1.8.6, starting with the collate method.

This method works on Lists, and groups the data in the list into sub-lists of a specified size.  As a simple example, we can group the numbers 1 to 10 into groups of size 4:

If you don’t want to carry extra values over into your grouped list, you can also set the keepRemainder variable to false like so:

Calls to collate can obviously be chained together, so to get a list grouped into 3 items per cell, and 2 cells per row, we could use something like:

It’s also possible to set the step size, which says how many elements along the list we advance when each group is created.  By default it is the same as the number of elements in a group, but we can create a simple sliding window by setting it to a lower value for example:

And combining collate with other groovy functions lets us do some funky manipulations such as this to generate a map from an ordered list:

and this to get the odd and even elements out of a list

Have fun!

@tim_yates

 
Blog comments powered by Disqus