32

How can I transform a list of tuples List[(A,B)] to a tuple of lists (List[A], List[B])?

I have tried for following but it looks crude and I was hoping there was a better way of doing this

  val flat: List[AnyRef] = aAndB.map{ x =>
    x.map(y => List(y._1, y._2))
  }.flatMap(x => x)

  val typeA: List[A] = flat.filter {
    case x: A => true
    case _ => false
  }.map(_.asInstanceOf[A])     

  val typeB: List[B] = flat.filter {
    case x: B => true
    case _ => false
  }.map(_.asInstanceOf[B])

1 Answer 1

66

You want unzip

scala> List((1,"a"), (3, "b"), (4, "d")).unzip
res1: (List[Int], List[String]) = (List(1, 3, 4),List(a, b, d))

Similarly there is an unzip3 for List[Tuple3[A, B, C]], though anything of higher arity you'd have to implement yourself.

scala> List((1,"a", true), (3, "b", false), (4, "d", true)).unzip3
res2: (List[Int], List[String], List[Boolean]) = (List(1, 3, 4),List(a, b, d),List(true, false, true))
Sign up to request clarification or add additional context in comments.

1 Comment

For higher arities you could use product-collections

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.