Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How best to get map from key list/value list in groovy?

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?

like image 565
ataylor Avatar asked Oct 06 '10 22:10

ataylor


People also ask

How do I add a key value pair to a map in Groovy?

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.

How to use map in Groovy script?

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.

Are Groovy maps ordered?

2. The each Method. In Groovy, maps created with the literal notation are ordered.


1 Answers

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 }
like image 99
tim_yates Avatar answered Oct 03 '22 00:10

tim_yates