How to merge two lists of tuples?

前端 未结 3 1568
没有蜡笔的小新
没有蜡笔的小新 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:34

    Alternatively you can also use mapValues to shorten the code.

    mapValues, as you can probably guess, allows you to re-map just the value for each (key, value) pair in the Map created by groupBy.

    In this case the function passed to mapValues reduces each (Char, Int) tuple to just the Int then sums the resulting List of Ints.

    (l1 ::: l2).groupBy(_._1).mapValues(_.map(_._2).sum).toList
    

    If the order of the output list needs to follow your example, just add sorted which relies on an Ordering[(Char, Int)] implicit instance.

    (l1 ::: l2).groupBy(_._1).mapValues(_.map(_._2).sum).toList.sorted
    

提交回复
热议问题