Combining two lists in Scala

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

    With Scalaz, this is a snap.

    import scalaz._
    import Scalaz._
    
    val l3 = (l1.map(_.swap).toMap |+| l2.map(_.swap).toMap) toList
    

    The |+| method is exposed on all types T for which there exists an implementation of Semigroup[T]. And it just so happens that the semigroup for Map[String, Int] is exactly what you want.

提交回复
热议问题