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]?
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)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With