如何迭代列表以创建到Map?

时间:2018-12-13 12:28:11

标签: scala

我有两个函数可以迭代列表并从中创建地图。

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

由于我要遍历myTextFile多次,因此我只想迭代一次并创建所需的两个映射。如何创建仅迭代一次并返回两个 Map[String, Color]的函数?

2 个答案:

答案 0 :(得分:6)

如果您真的只需要迭代一次并快速构建map,则可以使用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)))

答案 1 :(得分:4)

您可以折叠而做

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