Here's a seq of tuples in Scala
val t = Seq((1,2,3),(4,5,6))
I like to extract the first element of each tuple into its own sequence, i.e.,
Seq(1,4)
How do I do this in Scala?
Simply use map and transform each tuple to its first element:
t.map(x => x._1)
Or shorter:
t.map(_._1)
_i accessors: t map { case (n, _, _) => n }The general form to extract more than one columns:
def extractColumns3[T1, T2, T3](t: Seq[(T1, T2, T3)]): (Seq[T1], Seq[T2], Seq[T3]) =
t.foldLeft((Seq.empty[T1], Seq.empty[T2], Seq.empty[T3])) { (columns, row) ⇒
(columns._1 :+ row._1, columns._2 :+ row._2, columns._3 :+ row._3)
}