2014-10-03 78 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

相關問題