如何动态地将地图添加到列表?

时间:2014-10-03 20:15:56

标签: grails groovy

正如我在问题中描述的那样,我想动态地将地图添加到列表中,并避免使用相同的键添加地图我正在尝试这个

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

在现实生活场景中,字母将是用户添加的输入。

2 个答案:

答案 0 :(得分:4)

你走了:

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:[]]]

答案 1 :(得分:2)

使用find上的ListcontainsKey实例上的Map即可完成您的目标。 Maps的文档提供了更多信息。

def myList = []

["a", "b", "c", "c", "d", "e", "f", "a" ,"f"].each { letter ->
  def map = [:]
  if (!myList.find{ it.containsKey(letter) }) {
    map.put(letter, [])
    myList << map
  }
}

println myList​ // [[a:[]], [b:[]], [c:[]], [d:[]], [e:[]], [f:[]]]