2016-04-29 81 views
-1

我一直試圖從地圖中的鍵獲取特定值(這是一個列表)。我總是得到一個[null, null]。我嘗試了一切,從我在網上找到的東西。groovy:從地圖中的鍵中獲取一個值(這是一個列表)

// returns null 

def key = "name" 
def map = [name:[hello, there]] 
log.debug "map value ${map[key]}" 

// returns hello 

def key = "name" 
def map = [name:"hello"] 
log.debug "map value ${map[key]}" 

我如何獲得上述返回值列表,即[hello, there]

+0

'hello'和'there'可能被初始化爲null。這些變量在哪裏定義和初始化? –

回答

1

如果同時使用字符串(而不是不加引號,你有它在你的問題)地圖像這樣:

def key = "name" 
def map = [name:['hello', 'there']] 

然後map[key]將返回列表['hello', 'there']

assert map[key] == ['hello', 'there'] 
+0

工作!這樣的noob錯誤。如何在創建地圖時將這些值轉換爲字符串? @tim_yates – rond

+0

不知道,你不能解釋你的問題。如果你有'def hello ='hello''和'world',那麼你的代碼應該可以工作 –

+0

我正在另外一個地方創建地圖。創建地圖的代碼如下 - 'map = [姓名] .collect { \t \t [(it):it.numbers] \t}'。這裏的數字不是字符串。如果我找到一種方法將它們保存爲字符串,上述解決方案將適用於我。 @tim_yates – rond

1

你是缺少字符串值的引號。取而代之的

def key = "name" 
def map = [name:[hello, there]] 
log.debug "map value ${map[key]}" 

你需要

def key = "name" 
def map = [name:['hello', 'there']] 
log.debug "map value ${map[key]}" 
相關問題