Asimov
Asimov

Reputation: 73

Separating Text File Into Map In Scala

i'm pretty new to Scala, and i'm currently creating an app where I have to map a string representing a name with test scores represented by a list of ints.

Basically I have the following information:

Neil, 68, 79, 90
Buzz, 81, 52, 65
Michael, 95, 92, 81

in a text file named scores.txt i.e

val mapData = readTextFile("scores.txt")

and I'm looking to split this up after each person score and map this to a string and list of ints. I currently have a function named readTextFile which take the txt file as an input and from there i'm a bit stumped.

I know it should be similar to the following but I can't quite get it.

def readTextFile(filename: String): Map[String, List[Int]] = {
  var mapBuffer: Map[String, List[Int]] = Map()
  try {
    for (line <- Source.fromFile(filename).getLines()) {
      val splitline = line.split(",").map(_.trim).toList

      // add element to map buffer
      mapBuffer = mapBuffer ++ Map(splitline.head -> splitline.tail.head.toInt)
    }
  } catch {
    case ex: Exception => println("Sorry, an exception happened.")
  }
  mapBuffer
}

Any help would be greatly appreciated.

Thanks in advance, Steven.

Upvotes: 1

Views: 1144

Answers (2)

adamwy
adamwy

Reputation: 1239

I recommend using for comprehension over lines to make pairs and then converting them to a map:

def readTextFile(filename: String) = {
  val pairs = 
    for {
      line <- Source.fromFile(filename).getLines()
      split = line.split(",").map(_.trim).toList
      name = split.head
      scores = split.tail.map(_.toInt)
    } yield (name -> scores)
  pairs.toMap
}

Upvotes: 2

akuiper
akuiper

Reputation: 215137

You need to fix this line. splitline.tail.head.toInt only gets the second element in each row. You want to map and convert the tail of the splitline to List[Int]:

mapBuffer = mapBuffer ++ Map(splitline.head -> splitline.tail.map(_.toInt))

Upvotes: 1

Related Questions