In this post I describe the data transformation methods present in Groovy that usually have a completely different name in groovy. This may help you get your footing if you are coming from a background in Scala, Python, Ruby, Haskell, Rust, etc.
zip -> transpose
In other languages, you’ll often find a zip method that takes two lists and returns a list
of 2-arity tuples. In Groovy, this concept is covered by
transpose. Transpose, as the name
implies, performs a transposition of the provided list of lists. Additionally, transpose can
operate on an arbitrary number of lists. If the lists are of uneven lengths, the result will
be of the length of the shortest list.
map -> collect
The map concept, by which a function F(A) -> B is applied to the elements of a collection, is
collect in Groovy. As seen in the sample below, the original collection is not modified.
flatten -> flatten
Flatten, thankfully, has the same name one would expect. This recursively collapses collections into a single collection. Unfortunately, Groovy doesn’t have a Maybe / Option type, so flattening is only really useful for collapsing collections.
flatMap -> collectMany
A common idiom, given the
flatten utilities, is to map over collections and flatten the result
into a simple result. Many languages offer a flatMap to cover this. In Groovy, strangely, this is called
collectMany. I suppose the name describes what hey consider the common case - applying
collect to many
collections. In other languages, I would often map a collection, sometimes generating None (or an empty list)
for invalid or error conditions, and then flatten the result so only the valid results are present. This can
be accomplished in Groovy as well (though it’s not quite as straight forward).
collectMany does not recursively flatten!
filter -> findAll
In other languages, you use a filter operation to remove (or preserve, language depending) all members
of a collection meeting some criteria. In Groovy, the
findAll method accomplishes this.
any - any
As shown in a few examples above, the
any method can be used to assert that a predicate holds true
for at least one member of a collection.
all -> every
Also seen above, the
every method can be used to assert that a predicate holds true for all members
of a collection.
foldl -> inject
foldl concept is confusingly named
inject in groovy. This method takes a seed value and a two
param closure with the accumulator and the next value as params.
That’s all for now. I’ll probably update this list as I find more things worth noting.