如何在Groovy中为哈希映射的相同键添加值的列表。

huangapple go评论59阅读模式
英文:

how to add a list of value in case of same key for hashmap in groovy

问题

需要将特定键的值列表关联起来

例如,

listTags= ['A:1.1.1.1', 'B:1.1.2.1', 'C:1.1.3.1', 'B:1.1.4.1']

tags = [ : ]

listTags.each { it ->

  tags.put(it.split(':')[0], it.split(':')[1] )

}

println tags

结果: [A:1.1.1.1, B:1.1.4.1, C:1.1.3.1]

期望结果: [A:1.1.1.1, B:[1.1.2.1, 1.1.4.1], C:1.1.3.1]

有建议吗?
谢谢

英文:

A need to associate the list of values for specific keys

for example,

​listTags= ['A:1.1.1.1', 'B:1.1.2.1', 'C:1.1.3.1', 'B:1.1.4.1']

tags = [ : ]

listTags.each { it ->

  tags.put(it.split(':')[0], it.split(':')[1] )

}

println tags

Result: [A:1.1.1.1, B:1.1.4.1, C:1.1.3.1]

Expected Result: [A:1.1.1.1, B:[1.1.2.1, 1.1.4.1] , C:1.1.3.1]

Any suggestion?
thanks

答案1

得分: 1

你可以使用 "inject" 来实现这个。

在这里,我们将列表中的所有字符串拆分,然后从一个空映射开始,将值附加到每个键的列表中。


def result = listTags*.split(':')
    .inject([:].withDefault {[]}) { m, v ->
      m[v[0]] << v[1]
      m
    }
英文:

You can use inject for this.

Here, we split all strings in the list and then starting with an empty map, append the values to a list for each key

​listTags= [&#39;A:1.1.1.1&#39;, &#39;B:1.1.2.1&#39;, &#39;C:1.1.3.1&#39;, &#39;B:1.1.4.1&#39;]

def result = listTags*.split(&#39;:&#39;)
    .inject([:].withDefault {[]}) { m, v -&gt;
      m[v[0]] &lt;&lt; v[1]
      m
    }​​​

huangapple
  • 本文由 发表于 2023年4月19日 22:53:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76055951.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定