How to merge two lists of tuples?

前端 未结 3 1558
没有蜡笔的小新
没有蜡笔的小新 2020-12-31 12:06

I have two lists in Scala, how to merge them such that the tuples are grouped together?

Is there an existing Scala list API which can do this or need I do it by myse

3条回答
  •  爱一瞬间的悲伤
    2020-12-31 12:28

    You can try the following one-line:

    scala> ( l1 ++ l2 ).groupBy( _._1 ).map( kv => (kv._1, kv._2.map( _._2).sum ) ).toList
    res6: List[(Symbol, Int)] = List(('a,5), ('c,2), ('b,2), ('d,1))
    

    Where l1 and l2 are the lists of tuples you want merge.

    Now, the breakdown:

    • (l1 ++ l2) you just concatenate both lists
    • .groupBy( _._1) you group all tuples by their first element. You will receive a Map with the first element as key and lists of tuples starting with this element as values.
    • .map( kv => (kv._1, kv._2.map( _._2).sum ) ) you make a new map, with similar keys, but the values are the sum of all second elements.
    • .toList you convert the result back to a list.

    Alternatively, you can use pattern matching to access the tuple elements.

    ( l1 ++ l2 ).groupBy( _._1 ).map{
      case (key,tuples) => (key, tuples.map( _._2).sum ) 
    }.toList
    

提交回复
热议问题