[英]Convert List[Map[String,Map[String,Int]]] to Map[Int,Int] in Scala
Given the following: 给定以下内容:
val t: List[Map[String, Map[String, Int]]] = List(
Map("a" -> Map("m" -> 1, "l" -> 21)),
Map("a" -> Map("m" -> 2, "l" -> 22)),
Map("a" -> Map("m" -> 3, "l" -> 23)),
Map("a" -> Map("m" -> 4, "l" -> 24))
)
I want the result: 我想要结果:
Map(1->21,2->22,3->23,4->24)
What I have so far is: 到目前为止,我有:
val tt = (for {
(k,v) <- t
newKey = v("m")
newVal = v("l")
} yield Map(newKey -> newVal)).flatten.toMap
But this does not type check so Im missing some basic understanding since I cant understand why not? 但这不是类型检查,因此我无法理解为什么不能缺少基本的理解?
My questions are: 我的问题是:
You've got List[Map[...]]
, not Map[...]
so you want to unpack that first. 您有List[Map[...]]
而不是Map[...]
所以您想先将其拆包。
val tt = (for {
map <- t
(k, v) <- map
} ...)
t
.iterator
.flatMap(_.values)
.map { v => v("m") -> v("l") }
.toMap
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.