Created
August 12, 2011 17:41
-
-
Save tjweir/1142540 to your computer and use it in GitHub Desktop.
List to Map.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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))) | |
*/ |
jsuereth
commented
Aug 12, 2011
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))
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment