I very new to scala, i want to create Scala Map()
and Scala Seq()
by parsing csv files.
Input1.csv
-------------
State,Capital,Filter,Unique
MH,Mumbai,1,Yes
KA,Bengaluru,0,Yes
AP,Hydrabad,1,No
TS,Hydrabad,1,No
from Input1.csv file i want scala.collection.Map[K, V]
Map("MH" -> "Mumbai", "KA" -> "Bengaluru", "AP" -> "Hydrabad", "TS" -> "Hydrabad")
Input2.csv
-----------
Columns_Names
State
Capital
Filter
Unique
from Input2.csv file i want scala.collection.Seq[A]
Seq("State", "Capital", "Filter", "Unique")
How this can be done in scala?
You can do it something like:
import scala.io.Source
import scala.util.{Failure, Success, Try}
val source = Source.fromFile("Input1.csv")
val cityMap = Try(source
.getLines()
.toSeq
.tail
.map {
x =>
x.split(",") match {
case Array(code, capital, _, _) =>
code -> capital
}
}.toMap) match {
case Failure(exception) =>
exception.printStackTrace()
Map.empty[String, String]
case Success(value) =>
value
}
println(cityMap) // Map(MH -> Mumbai, KA -> Bengaluru, AP -> Hydrabad, TS -> Hydrabad)
source.close()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.