(1, 10), "b" -> (2, 20)) What would be the...">

How to map a tuple map to a map tuple in Scala?

Having

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

What would be the right Scala way to output

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

from a ?

+4
source share
3 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)) 
+13
source

I like Sean's answer, but if you want to, for some reason, cross your map only once and don’t want to use Scalaz, here is another solution:

 a.foldLeft((Map.empty[String, Int], Map.empty[String, Int])) { case ((a1, a2), (k, (v1, v2))) => (a1 + (k -> v1), a2 + (k -> v2)) } 
+6
source
 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) 
+2
source

Source: https://habr.com/ru/post/1401635/


All Articles