2015-09-23 23 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))