简体   繁体   English

scala将字符串列表转换为键/值映射

[英]scala turn List of Strings to a key/value map

I have a single ordered array of strings imported from an external system in the form of: 我有一个从外部系统导入的单个有序字符串数组,形式如下:

val l = List("key1", "val1", "key2", "val2", etc...)

what's the scala way to turn this into a map where I can get iterate over the keys and get the associated vals? 什么是scala方式将其转换为一个地图,我可以迭代键并获得相关的val?

thx 谢谢

My answer is similar to Daniel's but I would use collect instead of map : 我的回答类似于丹尼尔,但我会使用collect而不是map

l.grouped(2).collect { case List(k, v) => k -> v }.toMap

If you have a list with an unmatched key this won't throw an exception: 如果您有一个包含不匹配键的列表,则不会抛出异常:

scala>   val l = List("key1", "val1", "key2", "val2", "key3")
l: List[String] = List(key1, val1, key2, val2, key3)

scala> l.grouped(2).collect { case List(k, v) => k -> v }.toMap
res22: scala.collection.immutable.Map[String,String] = Map(key1 -> val1, key2 -> val2)

scala> l.grouped(2).map { case List(k, v) => k -> v }.toMap
scala.MatchError: List(key3) (of class scala.collection.immutable.$colon$colon)

Some context, grouped returns a List[List[String]] where every inner list has two elements: 一些上下文, grouped返回List[List[String]] ,其中每个内部列表都有两个元素:

scala> l.grouped(2).toList // the toList is to force the iterator to evaluate.
res26: List[List[String]] = List(List(key1, val1), List(key2, val2))

then with collect you match on the inner lists and create a tuple, at the end toMap transforms the list to a Map . 然后使用collect匹配内部列表并创建一个元组,最后toMap将列表转换为Map

l.grouped(2).map { case List(k, v) => k -> v }.toMap

You'll want to get them into pairs then provide them to a map 您需要将它们成对,然后将它们提供给地图

val lst: List[String] = List("key1", "val1", "key2", "val2")
val pairs = lst zip lst.tail
val m: Map[String,String] = pairs.toMap

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM