2013-10-10 18 views

回答

1
def map = [1:"A", 2:"B", 3:"C", 4:"D"] 
def keySet = [1, 2, 3] 

assert ['A', 'B', 'C'] == keySet.collect{map[it]} 
assert ['A', 'B', 'C'] == map.collectMany{k,v -> k in keySet ? [v] : []} 
assert ['A', 'B', 'C'] == map.findResults{k,v -> k in keySet ? v : null} 

如果我花了一些時間來解決這個問題,那麼很少有其他方法。 :)

0

我認爲你正在尋找方便的方法,如強大的Python切片。在groovy對於本發明的方法subMap內搭鍵列表:

Map m = [one: 1, two: 2, three: 3, four: 4] 

m.subMap(['two', 'three']) 
// Off course with groovy flexible syntax you may do simple: 
m.subMap('two', 'three') 
// Or even: 
m.subMap 'two', 'three', 'non-existent' 

兩種變體將返回['two':2, 'three':3]

如果我們請求不存在的密鑰,也不會有錯誤。

作爲論點,你可能真的提供任何收集不僅List,例如Range也可能是非常有用的。

您可能會在Klein Ikkink博客文章中找到一些其他示例:http://mrhaki.blogspot.ru/2009/10/groovy-goodness-getting-submap-from-map.html