Wednesday, September 25, 2019

Scala: creating nested maps of maps from nested Seq's of tuples

A messy solution to a problem when the map had to be created in a recursive function with branches.



scala> val x = List("s"->List("a"->1).groupBy(_._1).map { case (k,v) =>;(k,v.map(_._2))}).groupBy(_._1).map { case (k,v) =>; (k,v.map(_._2))}

x: scala.collection.immutable.Map[String,List[scala.collection.immutable.Map[String,List[Int]]]] = Map(s->List(Map(a->List(1))))

scala>; val x = List("s"->List("a"->1))
x: List[(String, List[(String, Int)])] = List((s,List((a,1))))

scala>; x.groupBy(_._1).map({case (k,v) =>; (k,v.flatMap(_._2).toMap)})

res13: scala.collection.immutable.Map[String,scala.collection.immutable.Map[String,Int]] = Map(s->Map(a->1))

scala>; val x = Seq(("s"->Seq("a"->1)),("t"->Seq("b"->2)))
x: Seq[(String, Seq[(String, Int)])] = List((s,List((a,1))), (t,List((b,2))))

scala>; x.groupBy(_._1).map{case (k,v) =>; (k, v.flatMap{_._2}.toMap)}
res44: scala.collection.immutable.Map[String,scala.collection.immutable.Map[String,Int]] = Map(t->Map(b->2), s->Map(a->1))

scala>; val x = List("s" ->; List("a" ->; 1))
x
scala> val x = Seq(("i" -> Seq("a" -> Seq("p" -> "x"))), ("j"-> Seq("b" -> Seq("q" -> "y"))))
x: Seq[(String, Seq[(String, Seq[(String, String)])])] = List((i,List((a,List((p,x))))), (j,List((b,List((q,y))))))

scala> x.groupBy(_._1).mapValues{ x => x.flatMap{ x => (x._2.map{x => (x._1, x._2.map{ case (k,v) => (k,v)}.toMap)})}.toMap}
res97: scala.collection.immutable.Map[String,scala.collection.immutable.Map[String,scala.collection.immutable.Map[String,String]]] = Map(j -> Map(b -> Map(q -> y)), i -> Map(a -> Map(p -> x)))

No comments:

Post a Comment