0

I have this

list {
  1,1
  1,2
  2,1
}

and I want to turn it into this

map {
  1 -> (1,2)
  2 -> (1)
}

What I tried so far:

val list = List((1,1),(1,2),(2,1))
var map: Map[Int, Seq[Int]] = Map()

for (e <- list) {
   if (map contains e._1)
    map = map + (e._1 -> (map(e._1) :+ e._2))
  else
    map = map + (e._1 -> Seq(e._2))
}

Needless to say it looks like someone spilled milk on my code. How to improve the situation?

gurghet
  • 7,591
  • 4
  • 36
  • 63
  • Closely related to http://stackoverflow.com/questions/8016750/convert-list-of-tuple-to-map-and-deal-with-duplicate-key. – heenenee Jul 26 '15 at 06:51

1 Answers1

6

You're looking for the .groupBy method:

scala> val list = List((1,1),(1,2),(2,1))
list: List[(Int, Int)] = List((1,1), (1,2), (2,1))

scala> val map = list.groupBy(_._1)
map: Map[Int,List[(Int, Int)]] = Map(2 -> List((2,1)), 1 -> List((1,1), (1,2)))

Then you simply need to map over the values and select the second element of each couple:

scala> val map = list.groupBy(_._1).mapValues(_.map(_._2))
map: Map[Int,List[Int]] = Map(2 -> List(1), 1 -> List(1, 2))
Marth
  • 23,920
  • 3
  • 60
  • 72