2012-09-27 94 views
1

我有一個用戶分配給團隊的場景。
不同ClientServices被分配到不同的團隊和
我們需要指定用戶這些球隊的輪轉方式
我試圖如下得到一個地圖,隊名和ClientServiceInstance的名單將被映射到解決它clientservice所以我可以做它進一步處理grails:將域類分配給另一個域類

def teamMap = [:] 
clientServicesList.each {clientServiceInstance-> 
      if(teamMap[clientServiceInstance.ownerTeam] == null){ 
       teamMap.putAt(clientServiceInstance.ownerTeam, new ArrayList().push(clientServiceInstance)) 
      }else{ 
       def tmpList = teamMap[clientServiceInstance.ownerTeam] 
       tmpList.push(clientServiceInstance) 
       teamMap[clientServiceInstance.ownerTeam] = tmpList 
      } 
     }  

but instead of pushing clientServiceInstance it pushes true. 

Any idea? 

回答

1

new ArrayList().push(clientServiceInstance)回報true,這意味着你把那到你teamMap什麼,而不是我想應該是一個列表?相反,你可能想

teamMap.putAt(clientServiceInstance.ownerTeam, [clientServiceInstance]) 

順便問一下,你的代碼是不是很Groovy的;)

你可以把它改寫爲類似

def teamMap = [:] 
clientServicesList.each { clientServiceInstance -> 
    if (teamMap[clientServiceInstance.ownerTeam]) { 
     teamMap[clientServiceInstance.ownerTeam] << clientServiceInstance 
    } else { 
     teamMap[clientServiceInstance.ownerTeam] = [clientServiceInstance] 
    } 
} 

雖然我敢肯定有更好的寫這些的方法。

2

我相信另一個版本是:

def teamMap = clientServicesList.inject([:].withDefault { [] }) { map, instance -> 
    map[ instance.ownerTeam ] << instance 
    map 
} 
+0

我就知道你有什麼聰明;) – doelleri