2014-10-03 76 views
0

正如我在想映射添加到列表中动态,并避免添加地图使用相同的密钥我想这如何动态地将地图添加到列表中?

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 

在真实的生活场景信问题描述将用户输入添加。

回答

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

现在,它的外观那么简单,由于 – user615274 2014-10-03 20:40:12

+0

@Opal呵呵,我们对此深感抱歉......完全错过了你的后续 – 2014-10-03 21:22:15

+0

没问题@tim_yates,谢谢! – Opal 2014-10-04 10:01:01

2

ListcontainsKey使用findMap实例将完成你在找什么。 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:[]]] 
+0

更简单,谢谢 – user615274 2014-10-03 20:40:46

相关问题