Scala: How to convert tuple elements to lists

user95947 picture user95947 · Sep 12, 2012 · Viewed 22k times · Source

Suppose I have the following list of tuples:

val tuples = listOfStrings.map(string => {
            val split = string.split(":")
            (split(0), split(1), split(2))
        })

I would like to get the split(0) in a list, split(1) in another list and so on. A simple way this could be achieved is by writing:

list1 = tuples.map(x => x._1).toList
list2 = tuples.map(x => x._2).toList
list3 = tuples.map(x => x._3).toList

Is there a more elegant (functional) way of achieving the above without writing 3 separate statements?

Answer

Régis Jean-Gilles picture Régis Jean-Gilles · Sep 12, 2012

This will give you your result as a list of list:

tuples.map{t => List(t._1, t._2, t._3)}.transpose

If you want to store them in local variables, just do:

val List(l1,l2,l3) = tuples.map{t => List(t._1, t._2, t._3)}.transpose

UPDATE: As pointed by Blaisorblade, the standard library actually has a built-in method for this: unzip3, which is just like unzip but for triples instead of pairs:

val (l1, l2, l3) = tuples.unzip3

Needless to say, you should favor this method over my hand-rolled solution above (but for tuples of arity > 3, this would still still apply).