Javier Laporta Javier Laporta - 6 months ago 22
Scala Question

Iterate over a list and add items another list SCALA

I have a list like this:

val list = List(("A", List("B", "C")),("B", List("A", "C", "D")))

And I want to return a list like this

newlist = List(("A","B",List("B","C")),("A","C",List("B","C")),("B","A",List("A", "C", "D")),("B","C",List("A", "C", "D")),("B","D",List("A", "C", "D")))

How can i do it with
? How can i do it with


This appears to be what you're after.

val lst = List(("A", List("B", "C")),("B", List("A", "C", "D")))
lst.flatMap{case (s,l) => l.map((s,_,l))}
res0: List[(String, String, List[String])] = List((A,B,List(B, C)), (A,C,List(B, C)), (B,A,List(A, C, D)), (B,C,List(A, C, D)), (B,D,List(A, C, D)))

If a for comprehension is might look like this.

for {
  t <- lst
  s <- t._2
} yield (t._1, s, t._2)