GroupBy in scala

后端 未结 5 1103
醉酒成梦
醉酒成梦 2021-01-02 23:52

I have

val a = List((1,2), (1,3), (3,4), (3,5), (4,5))

I am using A.groupBy(_._1) which is groupBy with the first element. Bu

5条回答
  •  悲哀的现实
    2021-01-03 00:38

    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.

提交回复
热议问题