hispaniccoder
hispaniccoder

Reputation: 397

How can I split a list of tuples scala

I have this list in Scala (which in reality has length 500):

List((1,List(1,2,3)), (2,List(1,2,3)), (3, List(1,2,3)))

What could I do so that I can make a new list which contains the following:

List((1,1), (1,2), (1,3), (2,1), (2,2), (2,3), (3,1), (3,2), (3,3))

Basically I wanna have a new list of tuples which will contain the first element of the old tuple and each element of the list inside the tuple. I am not sure how to start implementing this and this is why I have posted no code to show my attempt. I am really sorry, but I cant grasp this. I appreciate any help you can provide.

Upvotes: 0

Views: 654

Answers (3)

Exactly the same as @Andriy but using a for comprehension. Which in the end is exactly the same but is more readable IMHO.

val result = for {
  (x, ys) <- xs
  y <- ys
} yield (x, y) // You can also use x -> y

(Again, I would recommend you to follow any tutorial, this is a basic exercise which if you had understand how map & flatMap works you shouldn't have any problem)

Upvotes: 4

stefanobaghino
stefanobaghino

Reputation: 12794

It's probably worth mentioning that the solution by Andriy Plokhotnyuk can also be re-written as a for-comprehension:

val list = List((1,List(1,2,3)), (2,List(1,2,3)), (3, List(1,2,3)))

val pairs = for {
  (n, nestedList) <- list
  m <- nestedList
} yield (n, m)

assert(pairs == List((1,1), (1,2), (1,3), (2,1), (2,2), (2,3), (3,1), (3,2), (3,3)))

The compiler will effectively re-write the for-comprehension to a flatMap/map chain as described in another answer.

Upvotes: 1

Andriy Plokhotnyuk
Andriy Plokhotnyuk

Reputation: 7989

scala> val xs = List((1,List(1,2,3)), (2,List(1,2,3)), (3, List(1,2,3)))
xs: List[(Int, List[Int])] = List((1,List(1, 2, 3)), (2,List(1, 2, 3)), (3,List(1, 2, 3)))

scala> xs.flatMap { case (x, ys) => ys.map(y => (x, y)) }
res0: List[(Int, Int)] = List((1,1), (1,2), (1,3), (2,1), (2,2), (2,3), (3,1), (3,2), (3,3))

Upvotes: 2

Related Questions