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?
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?
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) }
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']