2012-09-02 56 views

回答

27

Groovy中接受幾乎所有的Java語法,所以有一個選擇範圍,如下圖所示:

// Java syntax 

Map<String,List> map1 = new HashMap<String,List>(); 
List list1 = new ArrayList(); 
list1.add("hello"); 
map1.put("abc", list1); 
assert map1.get("abc") == list1; 

// slightly less Java-esque 

def map2 = new HashMap<String,List>() 
def list2 = new ArrayList() 
list2.add("hello") 
map2.put("abc", list1) 
assert map2.get("abc") == list2 

// typical Groovy 

def map3 = [:] 
def list3 = [] 
list3 << "hello" 
map3.'abc'= list1 
assert map3.'abc' == list3 
13
def map = [:] 
map["stringKey"] = [1, 2, 3, 4] 
map["anotherKey"] = [55, 66, 77] 

assert map["anotherKey"] == [55, 66, 77] 
+5

另外: ' map.stringKey = [1,2,3,4]; map.anotherKey = [55,66,77]' – Will

5

一個額外的小片與地圖打交道時是有幫助的/列表中值地圖是groovy中地圖上的withDefault(Closure)方法。而不是做下面的代碼:

Map m = [:] 
for(object in listOfObjects) 
{ 
    if(m.containsKey(object.myKey)) 
    { 
    m.get(object.myKey).add(object.myValue) 
    } 
    else 
    { 
    m.put(object.myKey, [object.myValue] 
    } 
} 

你可以做到以下幾點:

Map m = [:].withDefault{key -> return []} 
for(object in listOfObjects) 
{ 
    List valueList = m.get(object.myKey) 
    m.put(object.myKey, valueList) 
} 

在默認可用於其他的東西爲好,但我覺得這是最常見的情況我。

API: http://www.groovy-lang.org/gdk.html

地圖 - > withDefault(關閉)

1

你不需要申報地圖常規內部識別它

def personDetails = [firstName:'John', lastName:'Doe', fullName:'John Doe'] 

// print the values.. 
    println "First Name: ${personDetails.firstName}" 
    println "Last Name: ${personDetails.lastName}" 

http://grails.asia/groovy-map-tutorial