Skip to content

@tjweir /gist:1142540
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
  l.groupBy(_._1).mapValues(_.map(_._2))
@tjweir
Owner

Do I pay you in hugs?

@jsuereth

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

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
Something went wrong with that request. Please try again.