示例代码:
package sparkstreaming
import scala.collection.mutable
object SparkStreamingDemo01 {
def main(args: Array[String]): Unit = {
// 两个Map的数据合并
val map1 = mutable.Map("a"->1, "b"->2, "c"->3, "e"->5)
val map2 = mutable.Map("a"->4, "b"->5, "d"->6)
val map3: mutable.Map[String, Int] = map2.foldLeft(map1) {
(map, kv) => {
val k = kv._1
val v = kv._2
map(k) = map.getOrElse(k, 0) + v
map
}
}
println(map3)
}
}
打印结果:
Map(e -> 5, b -> 7, d -> 6, a -> 5, c -> 3)
首先,采用模式匹配的方式(map, kv)分别匹配出:(map1, map2),debug代码图示:
遍历map2,取出每个key以及对应的value2
val k = kv._1
val v = kv._2
然后拿着k去map1取出对应的value1,能取到就是对应的值,取不到就是:0
val value1: Int = map.getOrElse(k, 0)
执行将value相加,如果:map【map1】集合中存在:k,就执行修改k对应的value值,如果不存在就执行加入键值对(k, value)操作
map(k) = value1 + v