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


Question

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?

1
8
6/2/2015 1:34:57 AM

Accepted Answer

Try this:

def keys = [1, 2, 3]
def values = ['a', 'b', 'c']
def pairs = [keys, values].transpose()

def map = [:]
pairs.each{ k, v -> map[k] = v }
println map

Alternatively:

def map = [:]
pairs.each{ map << (it as MapEntry) }
11
10/7/2010 3:59:08 AM

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 }

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon