Skip to content

Instantly share code, notes, and snippets.

@tjweir
Created August 12, 2011 17:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tjweir/1142540 to your computer and use it in GitHub Desktop.
Save tjweir/1142540 to your computer and use it in GitHub Desktop.
List to Map.
// 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
Copy link

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

@tjweir
Copy link
Author

tjweir commented Aug 12, 2011

Do I pay you in hugs?

@jsuereth
Copy link

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

@jsuereth
Copy link

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