Javier Laporta Javier Laporta - 3 months ago 8
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
map
? How can i do it with
for
?

Answer

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)
Comments