Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 205
navicore Avatar asked Dec 26 '22 05:12

navicore


1 Answers

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.

like image 181
Ende Neu Avatar answered Jan 10 '23 10:01

Ende Neu