Groovy Goodness: Transform Iterable Into A Map
Groovy 5 introduced some extra overloaded methods for the collectEntries
method, that can be used to transform an iterable object into a Map
.
You can now pass a closure or function as arguments to transform the original iterable element into the key and value for the resulting Map
. It is now also possible to pass a so-called collector Map
that will be used to extend with new key/value pairs.
Besides extra overloaded method signatures for collectEntries
Groovy 5 also adds the new methods withCollectedKeys
and withCollectedValues
. With the method withCollectedKeys
a closure or function can passed to create the keys for the new Map
based on the elements from the iterable. The value of the key/value pair is the unchanged element. You use the method withCollectedValues
to pass a closure or function to create the value for the new key/value pair in the resulting Map
. The key will be the original element from the iterable.