user8202693
user8202693

Reputation: 159

How to use map with list

So I have a population.csv file while looks like this:

country,population_size
Afghanistan,32758020
Albania,2889104
Algeria,39113313
American Samoa,55437
Andorra,79223
Angola,26920466
Antigua and Barbuda,98875
Argentina,42981515

I separated them line by line using this

val file_population = "population.csv"
def get_csv_file(file: String) : List[String] =
{
    val body = scala.io.Source.fromFile(file_population).mkString
    body.split("\n").toList
}

After that I need to split the strings according to the commas. This generate a Map from country names to population sizes.

I tried to do it and currently have the following:

def process_pops(lines: List[String]) : Map[String, Long] = 
{
    val seperated = for ( line <- lines ) yield (line.split(",").toList(0), (line.split(",").toList(1)).toLong )
    for ( i <- seperated)
    {
        val map = Map(seperated(0) -> seperated(1))
    }

} 

Please note that immutable map is only allowed but I am sure that it is wrong. Please help

Thanks for your time

Upvotes: 0

Views: 48

Answers (1)

Tyler
Tyler

Reputation: 18187

You can do this all a little bit nicer using some built-in functions like .toMap and pattern matching:

def process_pops(lines: List[String]) : Map[String, Long] = {

  // Remove the first line that is the headers
  val withoutHeaders = lines.tail

  // Map over each line
  val tuples: List[(String, Long)] = withoutHeaders.map(line => {

    // Split the line on the commas into its two parts
    val Array(country, pop) = line.split(",")

    // Return a tuple of type Tuple2[String, Long]
    country -> pop.toLong
  })

  // Convert the List of Tuples to a Map
  tuples.toMap
}

You could also do it with a fold, where we would start with an empty map, and for each line, add a new entry to the map:

def process_pops(lines: List[String]) : Map[String, Long] = {
  lines.tail.foldLeft(Map.empty[String, Long]) {
    case (map, line) =>
      val Array(country, pop) = line.split(",")
      map + (country -> pop.toLong)
  }
}

Upvotes: 3

Related Questions