首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在加特林中从列表转换为地图

在加特林中从列表转换为地图
EN

Stack Overflow用户
提问于 2015-09-24 02:48:28
回答 1查看 1.1K关注 0票数 0

我需要这样做:

代码语言:javascript
复制
{
“item” : “hardcoded_value”,
“item2” : “hardcoded_value”,
“item3” : “hardcoded_value”,
}

在exec块中,我尝试:

代码语言:javascript
复制
// 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"
}

但是在+=位置得到错误。

还尝试了:

代码语言:javascript
复制
theList.foreach(key =>  theMap += key -> "hardcoded_value" )

如何通过遍历列表将键和值插入到映射中?我是gatling和scala的新手。

EN

回答 1

Stack Overflow用户

发布于 2015-09-24 03:25:34

在更详细地研究了您的问题后,我意识到您不仅仅是在问如何将集合转换为地图。结合来自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?的答案,您可以执行以下操作:

代码语言:javascript
复制
List("first", "second", "third").zipWithIndex.map {
  case (item, index) => ("item" + index) -> item.toString
}
>res0: List[(String, String)] = List((item0,first), (item1,second), (item2,third))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32747231

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档