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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With