简体   繁体   English

Scala如何展平嵌套地图[String,Any]

[英]Scala How to flatten nested Map[String, Any]

I have nested map as below: 我有如下嵌套地图:

val x: Map[String, Any] = 
  Map("a" -> "apple", "b" -> "ball", "c" -> Map("x" -> "cat", "y" -> 12))

and I want to convert it into: 我想将其转换为:

Map("a" -> "apple", "b" -> "ball", "x" -> "cat", "y" -> 12)

However, if I try to invoke flatten to x then I get exception. 但是,如果我尝试将flatten调用到x,则会出现异常。

x.flatten
Error:(40, 14) No implicit view available from (String, Any) => scala.collection.GenTraversableOnce[B].
println(mx.flatten)
Error:(40, 14) not enough arguments for method flatten: (implicit asTraversable: ((String, Any)) => scala.collection.GenTraversableOnce[B])scala.collection.immutable.Iterable[B].
Unspecified value parameter asTraversable.
println(x.flatten)

So, how can I provide implicit view in order to flatten the above map? 因此,如何提供隐式视图以展平以上地图?

It's a bit strange you want to loose the information about 'c'. 您想丢掉有关“ c”的信息有点奇怪。
But anyway, the compiler is complaining because it does not know how to convert the (String,Any), your Key -> Value pair into a traversable and that is logical. 但是无论如何,编译器在抱怨,因为它不知道如何将(String,Any),您的Key-> Value对转换为可遍历的,这是合乎逻辑的。
You could provide the compiler with a hint that in case the 'Any' is a Map, it should only use the values and loose the key. 您可以向编译器提供提示,以防万一“ Any”是一个Map,它应该仅使用值并释放键。

For example: 例如:

x.flatten {
  case ((key, map : Map[String, Any])) => map
  case ((key, value)) => Map(key -> value)
}.toMap

This returns 这返回

Map(a -> apple, b -> ball, x -> cat, y -> 12)

Note: the 'toMap' is needed because the 'flatten' returns a List[(String,Any)]. 注意:因为'flatten'返回List [(String,Any)],所以需要'toMap'。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM