scala - 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)
但是我无法弄清楚如何将键列表展平为键,因此我得到了最终理想的形式。我该如何解决这个问题?
解决方案
如果您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
推荐阅读
- reactjs - 单击打开日历组件,在其他地方单击应关闭组件
- sql - SQL 连接表,如果没有链接则为空值
- c - 在 Gstreamer C API 中对 videoscale 元素使用上限
- javascript - 使用 JS 脚本的条形码扫描仪一段时间后 PC 冻结?
- docker - 如何使用 https://localhost:5001/api/Movies/getname 之类的 api 在 .net 核心中简单地调用从 container1 到 container2 的方法
- c# - 无法将通用记录转换为对象
- javascript - 获取日期时间输入字段的值
- lua - The rules for the # operator
- python - 如何将图像转换为感知器算法的输入向量?
- android - LiveDataReactiveStreams.fromPublisher 不工作