placplacboom placplacboom - 8 months ago 79
Scala Question

Scala - Convert List[String] to tuple List[(Int, Int)]

I would like to getLine from a Source and convert it to a tuple (Int, Int). I've did it using foreach.

val values = collection.mutable.ListBuffer[(Int, Int)]()

Source.fromFile(invitationFile.ref.file).getLines().filter(line => !line.isEmpty).foreach(line => {
val value = line.split("\\s")

values += ((value(0).toInt, (value(1).toInt)))

What's the best way to write the same code without use foreach?


Use map, it builds a new list for you:

.filter(line => !line.isEmpty)
.map(line => {
  val value = line.split("\\s")
  ((value(0).toInt, (value(1).toInt)))