I have the following tuples: (1,"3idiots",List("Action","Adventure","Horror") Which I need to convert into a list in the following format:
List(
(1,"3idiots","Action"),
(1,"3idiots","Adventure")
)
To add to previous answers, you can also use for-comprehension in this case; it might make things clearer IMHO:
for(
(a,b,l) <- ts;
s <- l
) yield (a,b,s)
So if you have:
val ts = List(
("a","1", List("foo","bar","baz")),
("b","2", List("foo1","bar1","baz1"))
)
You will get:
List(
(a,1,foo),
(a,1,bar),
(a,1,baz),
(b,2,foo1),
(b,2,bar1),
(b,2,baz1)
)
Assuming that you have more than one tuple like this:
val tuples = List(
(1, "3idiots", List("Action", "Adventure", "Horror")),
(2, "foobar", List("Foo", "Bar"))
)
and you want result like this:
List(
(1, "3idiots", "Action"),
(1, "3idiots" , "Adventure"),
(1, "3idiots", "Horror"),
(2, "foobar", "Foo"),
(2, "foobar", "Bar")
)
the solution for you would be to use a flatMap, which can convert a list of lists to a single list:
tuples.flatMap(t =>
t._3.map(s =>
(t._1, t._2, s)
)
)
or shorter: tuples.flatMap(t => t._3.map((t._1, t._2, _)))
flatMap)