简体   繁体   中英

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?

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.

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM