In python, I can do the following:
keys = [1, 2, 3]
values = ['a', 'b', 'c']
d = dict(zip(keys, values))
assert d == {1: 'a', 2: 'b', 3: 'c'}
Is there a nice way to construct a map in groovy, starting from a list of keys and a list of values?
Add Item to a Map The first way is using the square brackets for the key. This way useful if you have a dynamic key name for example the key name join with index. The second way is using a key separate with map name by a dot ".". Or this example also working in Groovy.
We can use the map literal syntax [k:v] for creating maps. Basically, it allows us to instantiate a map and define entries in one line. Notice that the keys aren't surrounded by quotes, and by default, Groovy creates an instance of java.
2. The each Method. In Groovy, maps created with the literal notation are ordered.
There's also the collectEntries
function in Groovy 1.8
def keys = [1, 2, 3]
def values = ['a', 'b', 'c']
[keys,values].transpose().collectEntries { it }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With