Search

Dark theme | Light theme

October 5, 2025

Groovy Goodness: Interleaving Elements From Collections

Groovy 5 adds the interleave method to the Iterable class. With this method you can interleave elements from two iterables. The result is a new List with elements where the first element is the first element of the first iterable and the second element the first element of the second iterable and so on. The size of the smallest collection is used to keep interleaving elements. Elements from the larger collection are ignored in the result.
If you want to have the items from the largest collection in the resulting list you can use the value true as second argument for the interleave method.

In the following example you can see usages of the interleave method:

def numbers = 1..4
def letters = 'a'..'d'

// Using the interleave element to combine
// elements from the numbers and letters collection.
assert numbers.interleave(letters) ==
  [1, 'a', 2, 'b', 3, 'c', 4, 'd']

// The size of the collection with the least elements
// determines the size of the resulting collection.
assert (1..3).interleave(letters) ==
  [1, 'a', 2, 'b', 3, 'c']

// With the extra argument set to `true` the elements
// from the biggest collection are appended to the result.
assert (1..10).interleave(letters, true) ==
    [1, 'a', 2, 'b', 3, 'c', 4, 'd', 5, 6, 7, 8, 9, 10]

Written with Groovy 5.0.0.