Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala nested maps - how to process?

Here is my nested map example with the data as literals. The program works as intended.

    var x = scala.collection.mutable.Map(
        ("Early", Map(("a", 1),  ("b", 2))), 
        ("Late",  Map(("x", 24), ("y", 25))))

for (ticker <- x.keys) {
    val trades = x(ticker)
    for (tradetime <- trades.keys) {
        val tradetotal = trades(tradetime)
        println(ticker + " | " + tradetime + " | " + tradetotal)
    }
    println(ticker + " | " + trades)
}

However, I want to eliminate the literals and read the above values from a csv file. Here is the csv:

Early,a,1 
Early,b,2
Late,x,24
Late,y,25

Here is the code to read the csv and print out the values in a way similar to the above program with literals.

  val bufferedSource = io.Source.fromFile("mapt.csv")
  val builder = StringBuilder.newBuilder

  for (line <- bufferedSource.getLines) {
    val cols = line.split(",").map(_.trim)
    println(s"${cols(0)}|${cols(1)}|${cols(2)}")
    var tmp = cols(0)   // s"${cols(0)}"

    val inner = scala.collection.mutable.Map.empty[String, Int]
    inner(cols(1)) = cols(2).toInt
    println(inner)

    val outer = scala.collection.mutable.Map.empty[String, String]
    outer(cols(0)) = inner
    println(outer)

  }
  bufferedSource.close

My code does not work. I’m struggling to find guidance on how to process nested maps. I am learning Scala. Grateful for any suggestions to create nested maps from csv file data.

I get the following error:

enter image description here

like image 618
Fred Avatar asked Sep 19 '25 14:09

Fred


1 Answers

val lines = scala.io.Source.fromFile("mapt.csv").getLines()
val row = lines.map(_.split(",").map(_.trim))
val outerMap=row.groupBy(_.head)
val result = outerMap.map{case (key,values)=> 
  key-> values.map(v=>(v(1)->v(2))).toMap}  
like image 153
Arnon Rotem-Gal-Oz Avatar answered Sep 21 '25 09:09

Arnon Rotem-Gal-Oz