Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map a map of tuples into a tuple of maps in Scala?

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?

like image 652
Ivan Avatar asked Nov 30 '22 15:11

Ivan


2 Answers

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))
like image 118
Sean Parsons Avatar answered Dec 04 '22 11:12

Sean Parsons


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))
}
like image 31
romusz Avatar answered Dec 04 '22 11:12

romusz