Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala List of tuples to flat list

Tags:

scala

I have list of tuple pairs, List[(String,String)] and want to flatten it to a list of strings, List[String].

like image 860
Andy Smith Avatar asked Nov 21 '14 18:11

Andy Smith


2 Answers

Some of the options might be: concatenate:

list.map(t => t._1 + t._2)

one after the other interleaved (after your comment it seems you were asking for this):

list.flatMap(t => List(t._1, t._2))

split and append them:

list.map(_._1) ++ list.map(_._2)
like image 181
Gábor Bakos Avatar answered Oct 02 '22 13:10

Gábor Bakos


In general for lists of tuples of any arity, consider this,

myTuplesList.map(_.productIterator.map(_.toString)).flatten

Note the productIterator casts all types in a tuple to Any, hence we recast values here to String.

like image 45
elm Avatar answered Oct 02 '22 12:10

elm