Convert a tuple to a list of the first item

Let's say I have a method that returns this.

Vector[ (PkgLine, Tree) ]()

I want to convert this to a PkgLines list. I want to remove the Tree. I do not see anything in the scala library that would allow me to do this. Anyone have any simple ideas? Thank.

+5
source share
2 answers
val list = vector.map(_._1).toList

If you have Tupel t, you can access its first element using t._1. Thus, with the help of the operation, mapyou effectively discard the trees and store PkgLinesdirectly. Then you just convert Vectorto List.

+16
source

Using the mapfirst element of a pair with a selector works:

scala> val v = Vector[(Int,String)]((5,"5"), (42,"forty-two"))
v: ... = Vector((5,5), (42,forty-two))

scala> v.map(_._1).toList
resN: List[Int] = List(5, 42)

unzip:

scala> val (ints,strings) = v.unzip
ints: scala.collection.immutable.Vector[Int] = Vector(5, 42)
strings: scala.collection.immutable.Vector[String] = Vector(5, forty-two)

scala> ints.toList
resN: List[Int] = List(5, 42)
+4

All Articles