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

时间:2016-04-01 21:12:07

标签: list scala dictionary collections

有人能帮我将Map [String,List [String]]转换为scala中的Map [String,String]吗?

这是Map [String,List [String]],如下所示:

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

需要将其转换为Map [String,String],如下所示:

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

2 个答案:

答案 0 :(得分:3)

如前所述,PFQueryTableView中的每个密钥都是唯一的。

那就是说,可以做的是将地图转换为一系列元组:

Map

会给你:

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

答案 1 :(得分:1)

地图无法重复显示。