如何将两个地图转换为单个地图

时间:2019-05-15 06:01:59

标签: scala

假设我有两个这样的地图

Map(("a" -> "x-100"), ("b" -> "x-200"), ("c" -> "x-300"))

Map(("a" -> "y-100"), ("b" -> "y-200"), ("c" -> "y-300"))

将它们转换为以下内容的最简单方法是什么(假设所有值都是唯一的,并且长度可能不同)?

Map(("x-100" -> "y-100"), ("x-200" -> "y-200"), ("x-300" -> "y-300"))

4 个答案:

答案 0 :(得分:4)

或者带有理解力和一些安全性

  for{
    (k, v1) <- m1
    v2 = m2.get(k)
    if (v2.isDefined)
  } yield (v1 -> v2.get)

这将返回Map(x-100 -> y-100, x-200 -> y-200, x-300 -> y-300)

选中ScalaFiddle

答案 1 :(得分:3)

您可以这样做:

val a = Map(("a" -> "x-100"), ("b" -> "x-200"), ("c" -> "x-300"))
val b = Map(("a" -> "y-100"), ("b" -> "y-200"), ("c" -> "y-300"))

def zipMaps(map1: Map[String, String], map2: Map[String, String]) = {
  for(key <- map1.keys ++ map2.keys)
     yield (key, map1.get(key), map2.get(key))
}

val result = zipMaps(a,b).map{
  case (k,Some(v1),Some(v2)) => (v1,v2)
  case (k,_ ,_)=> ("", "")
}.toMap.filterKeys(_ != "")
// result = Map(x-100 -> y-100, x-200 -> y-200, x-300 -> y-300)

答案 2 :(得分:3)

val m1 = Map(("a" -> "x-100"), ("b" -> "x-200"), ("c" -> "x-300"),("d" -> "ignored"))

val m2 = Map(("a" -> "y-100"), ("b" -> "y-200"), ("c" -> "y-300"))

m1.keySet.intersect(m2.keySet).map(k=>m1(k)->m2(k)).toMap

答案 3 :(得分:2)

val a = Map("a" -> "x-100", "b" -> "x-200", "c" -> "x-300")
val b = Map("a" -> "y-100", "b" -> "y-200", "c" -> "y-300")
val c = a.map {
  case (k, v) => v -> b(k)
}
println(c) // Map(x-100 -> y-100, x-200 -> y-200, x-300 -> y-300)