首页 > 解决方案 > Scala 以列表为键、字符串为值的地图展平

问题描述

我有一个特殊的情况,我想像这样声明简单的配置

val config = List((("a", "b", "c"), ("first")), 
               (("d", "e"), ("second")),
               (("f"), ("third")))

在运行时,我想要一张地图,其中的地图喜欢

"a" -> "first"
"b" -> "first"
"c" -> "first"
"d" -> "second"
"e" -> "second"
"f" -> "third"

使用toMap,我能够将 转换config为 Map

scala> config.toMap
res42: scala.collection.immutable.Map[java.io.Serializable,String] = Map((a,b,c) -> first, (d,e) -> second, f -> third)

但是我无法弄清楚如何将键列表展平为键,因此我得到了最终理想的形式。我该如何解决这个问题?

标签: scalacollections

解决方案


如果您config使用List代码构建您的结构非常简单:

val config = List(
  (List("a", "b", "c"), ("first")),
  (List("d", "e"), ("second")),
  (List("f"), ("third")))

config.flatMap{ case (k, v) => k.map(_ -> v) }.toMap

推荐阅读