public
Created

List to Map.

  • Download Gist
gistfile1.scala
Scala
1 2 3 4 5 6 7 8 9 10 11
// Turn this
val l:List[(Int, Int)] = List((111,333), (222,444), (111,555))
 
// Into
val m:Map[Int, List[Int]] = Map(111 -> List(333, 555), 222 -> List(444)))
 
// GroupBy seems about correct
/*
> l.groupBy(x => x._1)
res37: scala.collection.immutable.Map[Int,List[(Int, Int)]] = Map(222 -> List((222,444)), 111 -> List((111,333), (111,555)))
*/
  l.groupBy(_._1).mapValues(_.map(_._2))

Do I pay you in hugs?

want to say this, but withDefault is failing me...

  res0.foldLeft[Map[Int,List[Int]]](Map().withDefault(Nil)) { case (map, (key, value)) =>
     map.updated(key, value +: map(key))
   }
  java.lang.IndexOutOfBoundsException: 111

Got it:

scala> res0.foldLeft[Map[Int,List[Int]]](Map.empty) { case (map, (key, value)) =>
     |    map.updated(key, value +: map.getOrElse(key, List()))
     | }
res8: Map[Int,List[Int]] = Map(111 -> List(555, 222), 333 -> List(444))

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.