2

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?

2 Answers 2

11

Simply use map and transform each tuple to its first element:

t.map(x => x._1)

Or shorter:

t.map(_._1)
Sign up to request clarification or add additional context in comments.

1 Comment

Or, if you prefer not to use the _i accessors: t map { case (n, _, _) => n }
6

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

1 Comment

This solution has better performance for extracting more than one columns

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.