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:
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With