How to create a map out of two lists?

◇◆丶佛笑我妖孽 提交于 2020-11-29 11:33:36

问题


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) 

basically iterating thru both the lists and assigning key value pairs.

How to do it properly in Scala?


回答1:


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)


来源:https://stackoverflow.com/questions/27682783/how-to-create-a-map-out-of-two-lists

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!