欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

scala 两个Map 集合合并

程序员文章站 2024-03-02 19:44:10
...

//参考《快学scala》 集合操作 foldLeft page:180
package alogrithnm

import scala.collection.mutable.Map

object CombineTwoMap {

  def main(args: Array[String]): Unit = {

    val map1 = Map[String, Int]("a" -> 1, "b" -> 1, "c" -> 1)
//val map1 = Map[String, Int]("a" -> 1, "b" -> 1, "c" -> 1,"d"->1,"f"->1,"g"->1)
    val map2 = Map("a" -> 1, "z" -> 1, "c" -> 1, "d" -> 1)

    val result = combinerTwoMap(map1, map2)

    for ((k, v) <- result) {
      println(k + "  " + v)
    }
  }

  def combinerTwoMap(a: Map[String, Int], b: Map[String, Int]): Map[String, Int] = {
      (a /: b) {
        case (map, (k, v)) =>
          println(k + " " + v)
          map + (k -> (v + map.getOrElse(k, 0)))
        case _ =>
          println("not match")
          null
      }
    }
}

时间复杂度O(N)取决于size较小的那个map长度。