First, let's fix up what you've got already:
def parseFile(): Map[String, ListBuffer[String]] = { // always use interfaces (Map, not HashMap)
val userDataSet = scala.collection.mutable.HashMap.empty[String, ListBuffer[String]]
for (ln <- io.Source.stdin.getLines) {
val Array(id, date, number) = ln.split(",") // pattern match with names for clarity
val values = userDataSet.getOrElseUpdate(id, ListBuffer.empty)
values += number
}
userDataSet.toMap
}
Note that even if getOrElseUpdate
wasn't there, you'd still want to avoid the return-null-and-check thing by simply doing !userDataSet.contains(id)
. Alternatively, you could use .get(id)
, which returns an Option
.
Now for the functional solution. When you want to build up a collection by traversing some other collection, you probably want a "fold":
def parseFile(): Map[String, Vector[String]] = {
val lines = io.Source.stdin.getLines
lines.foldLeft(Map.empty[String, Vector[String]]) { (userDataSet, ln) =>
val Array(id, date, number) = ln.split(",") // pattern match with names for clarity
val existingValues = userDataSet.getOrElse(id, Vector.empty)
val updatedValues = existingValues :+ number
userDataSet + (id -> updatedValues) // update the Map with the new key/value
}
}