简体   繁体   English

Scala将Map [String,List [String]]转换为Map [String,String]

[英]Scala Convert a Map[String, List[String]] to a Map[String, String]

Would someone be able to help me convert Map[String, List[String]] to a Map[String, String] in scala? 有人可以帮助我在Scala中将Map [String,List [String]]转换为Map [String,String]吗?

Here is the Map[String, List[String]] as follows: 这是Map [String,List [String]],如下所示:

val pets: Map[String, List[String]] = Map(
    "home" -> List("cat", "dog", "fish"),
    "farm" -> List("cow", "horse"), 
    "wild" -> List("tiger", "elephant")
)

That needs to be converted to Map[String, String] as follows: 需要将其转换为Map [String,String],如下所示:

val pets2: Map[String, String] = Map(
    "home" -> "cat",
    "home" -> "dog",
    "home" -> "fish",
    "farm" -> "cow",
    "farm" -> "horse",
    "wild" -> "tiger",
    "wild" -> "elephant"
)

As mentioned before each key in a Map is unique. 如前所述, Map每个键都是唯一的。

That said, what you can do is convert the map to a sequence of tuples: 就是说,您可以做的就是将地图转换为元组序列:

pets.toSeq.flatMap { case (key, list) => list.map(key -> _) }

will give you: 会给你:

ArrayBuffer(
  (home,cat), 
  (home,dog), 
  (home,fish), 
  (farm,cow), 
  (farm,horse), 
  (wild,tiger), 
  (wild,elephant)
)

地图不能有重复的键。

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

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