0

Would someone be able to help me convert Map[String, List[String]] to a Map[String, String] in scala?

Here is the Map[String, List[String]] as follows:

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:

val pets2: Map[String, String] = Map(
    "home" -> "cat",
    "home" -> "dog",
    "home" -> "fish",
    "farm" -> "cow",
    "farm" -> "horse",
    "wild" -> "tiger",
    "wild" -> "elephant"
)
2
  • 1
    What you are asking is impossible. Maps can't have repeated keys. Commented Apr 1, 2016 at 21:15
  • But it does have a MultiMap Commented Apr 1, 2016 at 21:37

2 Answers 2

5

As mentioned before each key in a Map is unique.

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)
)
Sign up to request clarification or add additional context in comments.

Comments

1

Maps cannot have repeated keys.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.