How to create a map out of two lists?

后端 未结 1 683
灰色年华
灰色年华 2021-01-23 13:04

I have two lists

val a = List(1,2,3)
val b = List(5,6,7)

I\'d like to create a Map like:

val h = Map(1->5, 2->6, 3->7)         


        
相关标签:
1条回答
  • 2021-01-23 13:45

    You can zip the lists together into a list of tuples, then call toMap:

    (a zip b) toMap
    

    Note that if one list is longer than the other, it will be truncated.


    Example:

    val a = List(1, 2, 3)
    val b = List(5, 6, 7)
    
    scala> (a zip b) toMap
    res2: scala.collection.immutable.Map[Int,Int] = Map(1 -> 5, 2 -> 6, 3 -> 7)
    

    With truncation:

    val c = List("a", "b", "c", "d", "e")
    
    scala> (a zip c) toMap
    res3: scala.collection.immutable.Map[Int,String] = Map(1 -> a, 2 -> b, 3 -> c)
    
    (c zip a) toMap
    res4: scala.collection.immutable.Map[String,Int] = Map(a -> 1, b -> 2, c -> 3)
    
    0 讨论(0)
提交回复
热议问题