如我在问题中所述,我想将 map 动态添加到列表中,并避免使用相同的键添加 map ,我正在尝试这样做
def myList = []
["a", "b", "c", "c", "d", "e", "f", "a" ,"f"].each { letter ->
def map = [:]
//here I want to check if current letter exist as key in myList
//if it is true then avoid next code
map.put(letter, [])
myList << map
}
println myList
在现实生活中,字母将由用户添加。
最佳答案
干得好:
def myList = []
["a", "b", "c", "c", "d", "e", "f", "a" ,"f"].each { letter ->
if(!myList.find { it.keySet().contains(letter) })
myList << [(letter): []]
}
assert myList == [[a:[]], [b:[]], [c:[]], [d:[]], [e:[]], [f:[]]]
或者您可以简单地:
def myList = ["a", "b", "c", "c", "d", "e", "f", "a" ,"f"].unique().collect { [(it):[]] }
assert myList == [[a:[]], [b:[]], [c:[]], [d:[]], [e:[]], [f:[]]]
关于grails - 如何将 map 动态添加到列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26186147/