Suppose you have the following data structure:
val words = Seq("cat", "dog", "kid", "dee", "ding", "chip", "chord")
val grouped = words.groupBy(_.charAt(0))
What's a good functional way of creating another collection that's formed by taking each element of the sequences in grouped
in round robin? I.e. something like this:
Seq("kid", "dog", "cat", "dee", "chip", "ding", "chord")
or
Seq("dog", "cat", "kid", "dee", "chip", "ding", "chord")
We do not know in advance how many sequences will be in grouped
.
CodePudding user response:
You can flatten values using zipWithIndex
to combine them with index inside every group then group by that index and flatten again:
grouped.values
.flatMap(xs => xs.zipWithIndex)
.groupBy(_._2)
.values
.flatMap(_.unzip._1)