2015-10-05 102 views
1

我想查誰能夠拿出最好的Groovy-SH的方式來實現這一目標 -Groovy中 - 加入過濾器映射

def m1 = [["id":"1","o":"11"],["id":"1","o":"12"],["id":"2","o":"21"]] 
def m2 = [["o":"11","t":"t1"],["o":"11","t":"t2"],["o":"21","t":"t1"]] 

我想導致

[["id":"1","t":"t1"],["id":"1","t":"t2"],["id":"2","t":"t1"]] 

我目前的迭代地圖和做到這一點。我正在尋找一個解決方案,使用Gpath和findAll

謝謝, Sreehari。

回答

2

您可以transpose兩份名單,並從每個列表中的條目(idt):

def fn = { m1, m2 -> 
    return [m1,m2] 
     .transpose() 
     .collect { [ id: it.first().id, t: it.last().t ] } 
} 


def m1 = [["id":"1","o":"11"],["id":"1","o":"12"],["id":"2","o":"21"]] 
def m2 = [["o":"11","t":"t1"],["o":"11","t":"t2"],["o":"21","t":"t1"]] 


assert fn(m1, m2) == 
     [["id":"1","t":"t1"],["id":"1","t":"t2"],["id":"2","t":"t1"]] 
0

可以使用轉置到地圖拉鍊成對,然後通過地圖鍵結合對和過濾器:

[m1, m2] 
    .transpose() 
    .collect { (it[0] + it[1]).subMap(['id', 't']) } 

計算結果爲

[[id:1, t:t1], [id:1, t:t2], [id:2, t:t1]] 

這適用於groovysh使用Groovy-2.4 .4,與jdk7或jdk8。

+0

謝謝,我應該嘗試。什麼是subMap? – sreehari

+0

@sreehari:按鍵過濾地圖:http://mrhaki.blogspot.com/2009/10/groovy-goodness-getting-submap-from-map.html –

+0

我不能接受這個答案,因爲它沒有編譯併產生如上所述的期望結果。 – sreehari