Having
val a: Map[String, (Int, Int)] = Map("a" -> (1, 10), "b" -> (2, 20))
what would be the right Scala way to derive
val b: (Map[String, Int], Map[String, Int]) = (Map("a" -> 1, "b" -> 2), Map("a" -> 10, "b" -> 20))
from a
?
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))
I like Sean's answer, but if you wanted, for some reason to traverse your map only once and didn't want to use Scalaz, here's another solution:
a.foldLeft((Map.empty[String, Int], Map.empty[String, Int])) {
case ((a1, a2), (k, (v1, v2))) => (a1 + (k -> v1), a2 + (k -> v2))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With