Surender Raja Surender Raja - 3 months ago 6
Scala Question

Creating a Map by reading elements of List in Scala

I have some records in a List .
Now I want to create a new Map(Mutable Map) from that List with unique key for each record. I want to achieve this my reading a List and calling the higher order method called map in scala.

records.txt is my input file

100,Surender,2015-01-27
100,Surender,2015-01-30
101,Raja,2015-02-19


Expected Output :

Map(0-> 100,Surender,2015-01-27, 1 -> 100,Surender,2015-01-30,2 ->101,Raja,2015-02-19)


Scala Code :

object SampleObject{

def main(args:Array[String]) ={

val mutableMap = scala.collection.mutable.Map[Int,String]()
var i:Int =0
val myList=Source.fromFile("D:\\Scala_inputfiles\\records.txt").getLines().toList;
println(myList)
val resultList= myList.map { x =>
{
mutableMap(i) =x.toString()
i=i+1
}
}
println(mutableMap)

}

}


But I am getting output like below

Map(1 -> 101,Raja,2015-02-19)


I want to understand why it is keeping the last record alone .
Could some one help me?

elm elm
Answer

Consider

(for {
  (line, i) <- Source.fromFile(filename).getLines.zipWithIndex
} yield i -> line).toMap

where we read each line, associate an index value starting from zero and create a map out of each association.

Comments