[英]How to convert Map[Map[String,Int],Int] into Map[String,Int] in scala?
Eg. 例如。 Map[Map[String,Int],Int]
I need to convert it into Map[String,Int]
ie Int in value part of inner map is replaced with Int in value part of outer map. Map[Map[String,Int],Int]
我需要将其转换为Map[String,Int]
即内部地图的值部分的Int替换为外部地图的值部分的Int。
For example: 例如:
val innerMap = Map("a"->1)
val outerMap = Map(innerMap, 2)
Required result: 所需结果:
resultMap = Map("a"->2)
Even though you haven't answered my question about duplicate String
values, I'm going to guess that what you want is something like this. 即使您尚未回答有关重复的String
值的问题,我也会猜测您想要的是这样的东西。
val mmsii :Map[Map[String,Int],Int] =
Map(Map("a"->1)->11,Map("b"->2)->22)
mmsii.flatMap{case (m,v) => m.keys.map(_ -> v)}
Or, using the sometimes friendlier for
comprehension: 或者,使用有时更友好的方式for
理解:
for {
(m,v) <- mmsii
(k,_) <- m
} yield k->v
Keep in mind, if there are duplicate String
keys then only one String->Int
pair will be retained and the others will be lost. 请记住,如果有重复的String
键,则仅保留一对String->Int
对,而其他对则丢失。
You can leverage this solution to your problem 您可以利用此解决方案解决问题
val anotherMap = Map(Map("a" -> 1) -> 10, Map("b" -> 2) -> 11, Map("c" -> 3) -> 12)
anotherMap.flatMap {
case (keyMap, value) =>
keyMap map {
case (k, _) => Map(k -> value)
}
}
// res0: scala.collection.immutable.Iterable[scala.collection.immutable.Map[String,Int]] = List(Map(a -> 10), Map(b -> 11), Map(c -> 12))
Pretty much the same as @jwvh 's solution, just a little more explicit 与@jwvh的解决方案几乎相同,只是更加明确
val nestedMap: Map[Map[String, Int], Int] = Map(
Map("k1" -> 1) -> 11,
Map("k2" -> 2, "k3" -> 3) -> 22
)
val unnestedMap: Map[String, Int] = nestedMap.flatMap { (outerTuple: (Map[String, Int], Int)) =>
val innerMap: Map[String, Int] = outerTuple._1
val commonVal: Int = outerTuple._2
innerMap.map { (innerTuple: (String, Int)) =>
(innerTuple._1 -> commonVal)
}
}
print(unnestedMap)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.