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长度。
上一篇: Java枚举类enum介绍
下一篇: 深入理解Java中的弱引用