Anthony
Anthony

Reputation: 36008

how to iterate a list to create to Map?

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]?

Upvotes: 2

Views: 328

Answers (2)

Arnon Rotem-Gal-Oz
Arnon Rotem-Gal-Oz

Reputation: 25939

You can do that with fold

val (map1,map2) = myTextFile.
          foldLeft((Map[String,Color](),Map[String,Color]()))
            {case ((m1,m2),c)=>(m1 +(c.toShade->c), m2+(c.toQuantity->c))}

Upvotes: 4

Yevhenii Popadiuk
Yevhenii Popadiuk

Reputation: 1054

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)))

Upvotes: 6

Related Questions