From a map list view, to a real map in Scala

I want to convert Seq keys / values ​​to Map. The first element of the sequence is reserved, so the list of pairs starts at position 1 .

The question arises: is it possible to implement this function in a more functional way?

def list2Map(plainMap:Seq[String]) = {
  var map = Map[String, String]()
  var idx = 1;
  while(plainMap.size > idx) {
    val key = plainMap(idx)
    idx += 1
    val value = plainMap(idx)
    idx += 1

    map = map + (key -> value)
  }

  map
}

assert( list2Map( Seq("reserved slot","key0","value0","key1","value1","key2","value2") ) == Map( ("key0"->"value0"),("key1"->"value1"),("key2"->"value2") ) )

I am new to Scala and I know that there are many different ways to iterate through a collection, but I have not found a forEach way to read two elements to iterate starting from element 1.

PS: Thanks guys. I learn a lot with all the answers!

+4
source share
4 answers

list.drop(1).grouped(2).map { x => x.head -> x.last }.toMap

+4
source

You mean something like this:

val list = List("reserved slot", "key0", "value0", "key1", "value1", "key2", "value2")
val list4Map = list.tail.grouped(2).map { listBy2 => (listBy2(0), listBy2(1)) }.toList

val map = Map(list4Map: _*)
+2

Maybe you need a recursive option:

def seq2Map[T](seq: Seq[T]) = {
  def rec(seq: Seq[T], map: Map[T,T] = Map.empty[T,T]): Map[T,T] = seq match {
    case h :: t :: e => rec(e, map + (h -> t))
    case _ => map
  }
  rec(seq.tail)
}
0
source
(for { Seq(k, v) <- list.tail.grouped(2) } yield k -> v).toMap

also covers rear key

0
source

All Articles