Sure, here’s the translation: 用Groovy,从数组创建映射

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

Groovy, create map out of array

问题

我有一个元素数组,想要将其转换为映射。

  1. def vegetable = ['carrot', 'salad']
  2. def fruit = ['orange', 'apple']
  3. def all_food = group_a + group_b
  4. def my_map = [:]
  5. for (item in all_food) {
  6. my_map.put(item, "edible")
  7. }

有没有什么内联的方式来创建它呢?

  1. def my_map = all_food.collectEntries{[it, "edible"]}

或者类似的方法?

英文:

I have an array of elements and wanted to create a map out of it

  1. def vegetable = ['carrot', 'salad']
  2. def fruit = ['orange', 'apple']
  3. def all_food = group_a + group_b
  4. def my_map = [:]
  5. for(item in all_food) {
  6. my_map.put(item, "edible")
  7. }

any thought how to create it inline?

  1. def my_map = all_food.each{it, "edible"}

or smth similar ?

答案1

得分: 3

关于这部分代码:

  1. def result = all_food.collectEntries {[it, "可食"]}
英文:

How about

  1. def result = all_food.collectEntries {[it, "edible"]}

huangapple
  • 本文由 发表于 2020年8月28日 21:23:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/63634640.html
匿名

发表评论

匿名网友

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

确定