Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala transform list of tuples to a tuple of lists

Tags:

scala

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]) 
like image 907
Saket Avatar asked Dec 15 '14 15:12

Saket


People also ask

How do I create a tuple from a list in Scala?

length match { case 2 => toTuple2 case 3 => toTuple3 } def toTuple2 = elements match {case Seq(a, b) => (a, b) } def toTuple3 = elements match {case Seq(a, b, c) => (a, b, c) } } val product = List(1, 2, 3). toTuple product. productElement(5) //runtime IndexOutOfBoundException, Bad ! val tuple = List(1, 2, 3).

How to convert two list into tuple?

1) Using tuple() builtin function tuple () function can take any iterable as an argument and convert it into a tuple object. As you wish to convert a python list to a tuple, you can pass the entire list as a parameter within the tuple() function, and it will return the tuple data type as an output.

What is the use of tuple in Scala?

In Scala, a tuple is a value that contains a fixed number of elements, each with its own type. Tuples are immutable. Tuples are especially handy for returning multiple values from a method.

What is the difference between list and tuple in Scala?

Lists are mutable(values can be changed) whereas tuples are immutable(values cannot be changed).


1 Answers

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)) 
like image 96
Michael Zajac Avatar answered Sep 21 '22 20:09

Michael Zajac