0

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?

2 Answers 2

3
val mm: Map[Int, String] = Source.fromFile(filename).getLines
  .zipWithIndex
  .map({ case (line, i) => i -> line })(collection.breakOut)

Here the (collection.breakOut) is to avoid the extra parse caused by toMap.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for this neat approach, I also just found out what went wrong in my code, just edited my code again and it worked.Thanks again
1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.