GroupBy in scala

You can do that by following up with mapValues (and a map over each value to extract the second element):

scala> a.groupBy(_._1).mapValues(_.map(_._2))
res2: scala.collection.immutable.Map[Int,List[Int]] = Map(4 -> List(5), 1 -> List(2, 3), 3 -> List(4, 5))

Make life easy with pattern match and Map#withDefaultValue:

scala> a.foldLeft(Map.empty[Int, List[Int]].withDefaultValue(Nil)){ 
         case(r, (x, y)) => r.updated(x, r(x):+y) 
       }
res0: scala.collection.immutable.Map[Int,List[Int]] = 
      Map(1 -> List(2, 3), 3 -> List(4, 5), 4 -> List(5))

There are two points:

  1. Map#withDefaultValue will get a map with a given default value, then you don't need to check if the map contains a key.

  2. When somewhere in scala expected a function value (x1,x2,..,xn) => y, you can always use a pattern matching case(x1,x2,..,xn) => y here, the compiler will translate it to a function auto. Look into 8.5 Pattern Matching Anonymous Functions for more information.

Sorry for my poor english.


As a variant:

a.foldLeft(Map[Int, List[Int]]()) {case (acc, (a,b)) => acc + (a -> (b::acc.getOrElse(a,List())))}

Tags:

Scala