如何将元组映射映射到Scala中的映射元组?

时间:2012-03-15 15:23:02

标签: scala collections mapping

具有

val a: Map[String, (Int, Int)] = Map("a" -> (1, 10), "b" -> (2, 20))

什么是正确的Scala派生方式

val b: (Map[String, Int], Map[String, Int]) = (Map("a" -> 1, "b" -> 2), Map("a" -> 10, "b" -> 20))

来自a

3 个答案:

答案 0 :(得分:13)

scala> val b = (a.mapValues(_._1), a.mapValues(_._2))
b: (scala.collection.immutable.Map[String,Int], scala.collection.immutable.Map[String,Int]) = (Map(a -> 1, b -> 2),Map(a -> 10, b -> 20))

答案 1 :(得分:6)

我喜欢Sean的回答,但是如果你想要,由于某种原因只能遍历你的地图一次并且不想使用Scalaz,这是另一个解决方案:

a.foldLeft((Map.empty[String, Int], Map.empty[String, Int])) {
  case ((a1, a2), (k, (v1, v2))) => (a1 + (k -> v1), a2 + (k -> v2))
}

答案 2 :(得分:2)

import scalaz._
import Scalaz._

scala> val m = Map("a" -> (1, 10), "b" -> (2, 20))
m: scala.collection.immutable.Map[java.lang.String,(Int, Int)] = Map(a -> (1,10), b -> (2,20))

scala> val (a, b) = m.toSeq foldMap { case (k, (v1, v2)) => (Map(k -> v1), Map(k -> v2)) }
a: scala.collection.immutable.Map[java.lang.String,Int] = Map(b -> 2, a -> 1)
b: scala.collection.immutable.Map[java.lang.String,Int] = Map(b -> 20, a -> 10)