2

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.

Nico
  • 25
  • 4

1 Answers1

0

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

theMap 
  .map(t => 0.until(t._2).map(_ => t._1))
  .flatten
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • Thanks, using a range to fill it, perfectly fits into 'a nicer way' and I learned something new from your post, thanks! – Nico Oct 17 '20 at 00:57