Creating a Map [String, List [String]] from the List [(String, String)]

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 is that if I use toMap() directly, values ​​with the same keys are deleted.

History so far:

 list.groupBy(el => el).map(el => el._1 -> ?) 
+4
source share
1 answer

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())) } 
+4
source

Source: https://habr.com/ru/post/1443840/


All Articles