Surender Raja Surender Raja - 1 year ago 88
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


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;
val resultList= { x =>
mutableMap(i) =x.toString()



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 Source


(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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download