Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/clojure/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 如何迭代列表以创建映射?_Scala - Fatal编程技术网

Scala 如何迭代列表以创建映射?

Scala 如何迭代列表以创建映射?,scala,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,所以我只想迭代一次并创建所需的两个映射

我有两个函数,它们迭代一个列表并从中生成一个映射

  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]

如果您确实需要只迭代一次并动态构建
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)))

你可以用折叠来做

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