GroupBy in scala

后端 未结 5 1122
醉酒成梦
醉酒成梦 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:42

    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))
    

提交回复
热议问题