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

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

Groovy, create map out of array

问题

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

def vegetable = ['carrot', 'salad']
def fruit = ['orange', 'apple']
def all_food = group_a + group_b

def my_map = [:]
for (item in all_food) {
    my_map.put(item, "edible")
}

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

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

或者类似的方法?

英文:

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

def vegetable = ['carrot', 'salad']
def fruit = ['orange', 'apple']
def all_food = group_a + group_b

def my_map = [:]
for(item in all_food) {
    my_map.put(item, "edible")
}

any thought how to create it inline?

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

or smth similar ?

答案1

得分: 3

关于这部分代码:

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

How about

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:

确定