2015-09-23 19 views
0

我需要形成這樣的:轉換爲從列表中映射加特林

{ 
「item」 : 「hardcoded_value」, 
「item2」 : 「hardcoded_value」, 
「item3」 : 「hardcoded_value」, 
} 

在EXEC塊我想:

// list with items [「item1」, 「 item2」, 「 item3」] 
val theList = session("itemNames").as[List[String]] 

val theMap = Map.empty[String,String]  // empty map 

// add items from list in map 
theList.foreach{ key => 
         | theMap += key -> "hardcoded_value" 
} 

但得到錯誤的+ =位置。

也試過:

theList.foreach(key => theMap += key -> "hardcoded_value") 

如何通過遍歷一個列表中插入鍵和值到地圖嗎?我是加特林和斯卡拉的新手。

回答

0

在更詳細地查看您的問題之後,我意識到您不只是詢問如何將集合轉換爲地圖。結合How can I use map and receive an index as well in Scala?Scala best way of turning a Collection into a Map-by-key?的回答,您可以執行以下操作:

List("first", "second", "third").zipWithIndex.map { 
    case (item, index) => ("item" + index) -> item.toString 
} 
>res0: List[(String, String)] = List((item0,first), (item1,second), (item2,third))