Combining two lists in Scala

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

    val l = l1 ::: l2
    val m = Map[String, Int]()
    (m /: l) {
      case (map, (i, s)) => { map.updated(s, i + (map.get(s) getOrElse 0))}
    }.toList // Note: Tuples are reversed.
    

    But I suppose there is a more elegant way to do the updated part.

提交回复
热议问题