Combining two lists in Scala

后端 未结 8 827
北海茫月
北海茫月 2021-01-04 00:58

From 2 lists of the form List[(Int, String):

l1 = List((1,\"a\"),(3,\"b\"))
l2 = List((3,\"a\"),(4,\"c\"))

how can I combine t

8条回答
  •  日久生厌
    2021-01-04 01:39

    How about,

    (l1 ++ l2).groupBy(_._2).mapValues(_.unzip._1.sum).toList.map(_.swap)
    

    Unpacking this a little on the REPL helps to show what's going on,

    scala> l1 ++ l2
    res0: List[(Int, java.lang.String)] = List((1,a), (3,b), (3,a), (4,c))
    
    scala> res0.groupBy(_._2)
    res1: ... = Map(c -> List((4,c)), a -> List((1,a), (3,a)), b -> List((3,b)))
    
    scala> res1.mapValues(_.unzip)
    res2: ... = Map(c -> (List(4),List(c)), a -> (List(1, 3),List(a, a)), b -> (List(3),List(b)))                         
    
    scala> res1.mapValues(_.unzip._1)                                                                                                                                                                      
    res3: ... = Map(c -> List(4), a -> List(1, 3), b -> List(3))                                                                                    
    
    scala> res1.mapValues(_.unzip._1.sum)
    res4: ... = Map(c -> 4, a -> 4, b -> 3)                                                                                                               
    
    scala> res4.toList                                                                                                                                                                                     
    res5: List[(java.lang.String, Int)] = List((c,4), (a,4), (b,3))                                                                                                                                        
    
    scala> res5.map(_.swap)
    res6: List[(Int, java.lang.String)] = List((4,c), (4,a), (3,b))
    

提交回复
热议问题