4

I got the following list of pairs:

 List(("US","New York"),("England","London"),("US","Los Angeles"),("England","Manchester"),("US","Washington"))

I need to generate a Map[Country, List[Cities]]:

Map("US" -> List("New York", "Los Angeles", "Washington"), "England" -> List("London", "Manchester"))

The problem that if I use toMap() directly the values with same keys are removed.

The story so far:

list.groupBy(el => el).map(el => el._1 -> ?)
0

1 Answer 1

4

using groupBy:

list.groupBy(_._1).mapValues(_.map(_._2))

using fold:

list.foldLeft(Map.empty[String, List[String]]) { case (m, (k, v)) =>
  m.updated(k, v :: m.getOrElse(k, List()))
}
Sign up to request clarification or add additional context in comments.

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.