开发者

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

开发者 https://www.devze.com 2023-01-19 04:20 出处:网络
In python, I can do the following: keys = [1, 2, 3] values = [\'a\', \'b\', \'c\'] d = dict(zip(keys, 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开发者_如何学Go groovy, starting from a list of keys and a list of values?


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 }


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']
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号