2012-09-02 3 views

답변

27

그루비 거의 모든 자바 구문을 허용, 그래서 아래 그림과 같이 선택의 스펙트럼이있다 :지도를 처리 할 때의 값으로/목록에 도움이됩니다

// 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 = [:].withDefault{key -> return []} 
for(object in listOfObjects) 
{ 
    List valueList = m.get(object.myKey) 
    m.put(object.myKey, valueList) 
} 

뿐만 아니라 다른 것들에 사용할 수 있습니다,하지만 난이 날의 가장 일반적인 사용 방법으로 찾을 수 있습니다 :

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] 
    } 
} 

다음과 같은 작업을 수행 할 수 있습니다.

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

관련 문제