GroupBy in scala

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

    You can also do it with a foldLeft to have only one iteration.

    a.foldLeft(Map.empty[Int, List[Int]])((map, t) => 
      if(map.contains(t._1)) map + (t._1 -> (t._2 :: map(t._1))) 
      else map + (t._1 -> List(t._2)))
    
    scala.collection.immutable.Map[Int,List[Int]] = Map(1 -> List(3, 2), 3 ->
           List(5, 4), 4 -> List(5))
    

    If the order of the elements in the lists matters you need to include a reverse.

    a.foldLeft(Map.empty[Int, List[Int]])((map, t) => 
      if(map.contains(t._1)) (map + (t._1 -> (t._2 :: map(t._1)).reverse)) 
      else map + (t._1 -> List(t._2)))
    
    scala.collection.immutable.Map[Int,List[Int]] = Map(1 -> List(2, 3), 3 ->
           List(4, 5), 4 -> List(5))
    

提交回复
热议问题