Home > Blockchain >  want to convert list of strings into map in Scala. Ex: list(1,2,3,4) into Map(1->2,3->4) can a
want to convert list of strings into map in Scala. Ex: list(1,2,3,4) into Map(1->2,3->4) can a

Time:11-08

Anyone help me to convert list of strings into map by indexes (0,1) as key-value pair and index(2,3) as 2nd pair and index(3,4) as 3rd pair. Ex: List("asd","fgh","qwe","tyu") into Map("asd"->"fgh", "qwe"->"tyu")

CodePudding user response:

A simple matter of turning pairs into tuples and calling .toMap on it.

val myMap = myList.grouped(2)
                  .collect{
                    case List(a,b) => (a,b)
                    case List(x) => (x,"")
                  }.toMap

Note: This doesn't check for duplicate keys so an input like List("a","b","a","c") will result in Map("a" -> "c").

CodePudding user response:

This can be done using three standard library methods:

val list = List("asd","fgh","qwe","tyu")

list
  .grouped(2) // Group elements in pairs
  .map {      // Convert pairs to tuples
    case a :: b :: Nil => a -> b   // Normal values to tuple
    case a :: Nil      => a -> ""  // Final value if list size is odd
  }
  .toMap // Convert List[(A, B)] to Map[A,B]

Since you are creating a Map, if the same even value appears more than once there will be duplicate keys, and only the final pair will be in the resulting Map.

(If you are new to Scala, the syntax a -> b is another way of creating a tuple (a, b), and can be used in cases like this to make it clear that there is a key-value relationship between values in a pair)

  • Related