Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to iterate a list to create to Map?

Tags:

scala

I have two functions that iterate a list and make a map out of it.

  def indexedShade: Map[String, Color] =
    myTextFile.map(c => (c.toShade, c)).toMap
  def indexedQuantity: Map[String, Color] =
    myTextFile.map(c => (c.toQuantity, c)).toMap

Since I'm iterating over myTextFile multiple times, I would like to just iterate once and create the two maps needed. How can I create a function that only iterates once and returns two Map[String, Color]?

like image 618
Anthony Avatar asked Dec 06 '25 23:12

Anthony


1 Answers

If you really need to iterate only once and build map's on fly, you can do it with foldLeft:

val (indexedShade, indexedQuantity) = myTextFile
  .foldLeft((Map.empty[String, Color], Map.empty[String, Color]))((acc, cur) => 
    (acc._1 + (cur.toShade -> cur), acc._2 + (cur.toQuantity -> cur)))
like image 92
Yevhenii Popadiuk Avatar answered Dec 08 '25 16:12

Yevhenii Popadiuk