如何在scala中一个接一个地合并或插入两个地图?

时间:2019-05-10 03:20:13

标签: scala merge maps

我想将两个地图合并到一个地图列表中,如下所示:


val map1 = {"a" -> 1, "b" -> 2, "c" -> 3}
val map2 = {"x" -> 10, "y" -> 20, "z" -> 30}

val res = [{"a" ->1, "x" -> 10},{"b" -> 2, "y" -> 20},{"c" -> 3, "z" -> 30}]

2 个答案:

答案 0 :(得分:2)

也许是这样的:

val map1 = Map("a" -> 1, "b" -> 2, "c" -> 3)
val map2 = Map("x" -> 10, "y" -> 20, "z" -> 30)


(map1.toList, map2.toList).zipped.map{
   case (a,b) => Map(a,b)
}

答案 1 :(得分:1)

您也可以尝试以下方法:

val map1 = Map("a" -> 1, "b" -> 2, "c" -> 3)
val map2 = Map("x" -> 10, "y" -> 20, "z" -> 30)

val res = for ((i, j) <- map1 zip map2) yield Map(i, j)