Scala两个地图合并

时间:2017-02-23 10:34:38

标签: scala hashmap

如何合并如下地图:

val map1 = Map(1 -> "a", 2 -> "b")
val map2 = Map("a" -> "A", "b" -> "B")

合并后。

Merged = Map( 1 -> List("a", "A"), 2 -> List("b", "B"))

可以是List,Set或任何其他具有size属性的集合。

2 个答案:

答案 0 :(得分:1)

给出两张value1key2

的地图
scala> val x = Map(1 -> "a", 2 -> "b")
x: scala.collection.immutable.Map[Int,String] = Map(1 -> a, 2 -> b)

scala> val y = Map("a" -> "A", "b" -> "B")
y: scala.collection.immutable.Map[String,String] = Map(a -> A, b -> B)

合并为Map(k1 -> List(v1, v2))

scala> val z = x.map { case (k1, v1) => (k1, List(v1, y(v1))) }
z: scala.collection.immutable.Map[Int,List[String]] = Map(1 -> List(a, A), 2 -> List(b, B))

你基本上需要从第一张地图获取价值然后查找第二张地图,然后只需创建一张列表(v1,v2)。

答案 1 :(得分:1)

试试这个

scala> val map1 = Map(1 -> "a", 2 -> "b") 
map1: scala.collection.immutable.Map[Int,String] = Map(1 -> a, 2 -> b)

scala> val map2 = Map("a" -> "A", "b" -> "B")
map2: scala.collection.immutable.Map[String,String] = Map(a -> A, b -> B)

scala> map1.zip(map2).map(x=>x._1._1 -> List(x._2._1,x._2._2))
res44: scala.collection.immutable.Map[Int,List[String]] = Map(1 -> List(a, A), 2 -> List(b, B))