placplacboom placplacboom - 1 year ago 198
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?

Answer Source

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)))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download