navicore
navicore

Reputation: 2109

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?

thx

Upvotes: 5

Views: 8770

Answers (3)

Ende Neu
Ende Neu

Reputation: 15773

My answer is similar to Daniel's but I would use collect instead of 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:

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.

Upvotes: 8

Cameron Cook
Cameron Cook

Reputation: 67

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

Upvotes: -1

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297155

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

Upvotes: 3

Related Questions