Combining two lists in Scala

后端 未结 8 774
北海茫月
北海茫月 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:56

    An alternative to Miles Sabin's answer using Scala 2.13's new groupMapReduce method which is (as its name suggests) an equivalent (more efficient) of a groupBy followed by mapValues and a reduce step:

    (l1 ::: l2).groupMapReduce(_._2)(_._1)(_ + _).toList.map(_.swap)
    // List[(Int, String)] = List((3,b), (4,a), (4,c))
    

    This:

    • prepends l1 to l2

    • groups elements based on their second tuple part (group part of groupMapReduce)

    • maps grouped values to their first tuple part (map part of groupMapReduce)

    • reduces values (_ + _) by summing them (reduce part of groupMapReduce)

    • and finally swaps tuples' parts.

    This is an equivalent version performed in one pass (for the group/map/reduce part) through the List of:

    (l1 ::: l2).groupBy(_._2).mapValues(_.map(_._1).reduce(_ + _)).toList.map(_.swap)
    

提交回复
热议问题