ataylor
ataylor

Reputation: 66059

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?

Upvotes: 9

Views: 6323

Answers (3)

tim_yates
tim_yates

Reputation: 171084

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 }

Upvotes: 22

NullUserException
NullUserException

Reputation: 85458

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) }

Upvotes: 12

Ted Naleid
Ted Naleid

Reputation: 26801

There isn't anything built directly in to groovy, but there are a number of ways to solve it easily, here's one:

def zip(keys, values) {
    keys.inject([:]) { m, k -> m[k] = values[m.size()]; m } 
}

def result = zip([1, 2, 3], ['a', 'b', 'c'])
assert result == [1: 'a', 2: 'b', 3: 'c']

Upvotes: 5

Related Questions