Scala converting Map[String, Int]("a"->2, "b"->1) to Sequence Seq("a", "a", "b")

Viewed 48

I have for example a map such as Map("a" -> 2, "b" -> 4). I want to convert it to a Sequence such that Seq("a", "a", "b", "b", "b", "b").

Im currently doing this:

(for (e <- theMap) yield
      for (_ <- 0 until e._2) yield e._1).flatten).toSeq

My question is: what would be a better/more sophisticated approach to doing this because I am pretty sure the a double yield for loop is not necessary and scala allows you to it in a 'nicer' way.

1 Answers

I would use Range to repeat the character and "replace" yield with map:

theMap 
  .map(t => 0.until(t._2).map(_ => t._1))
  .flatten
Related