从加特林的列表转换为地图

时间:2015-09-23 18:48:28

标签: scala scala-collections gatling

我需要形成这个:

{
“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" )

如何通过迭代列表将键和值插入到地图中?我是gatling和scala的新手。

1 个答案:

答案 0 :(得分: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))