簡單合併code
val map1 = Map("key1" -> 1, "key2" -> 3, "key3" -> 5) val map2 = Map("key2" -> 4, "key3" -> 6, "key5" -> 10) println(map1 + ("key1" -> 3)) println(map1 ++ map2)
結果get
Map(key1 -> 3, key2 -> 3, key3 -> 5) Map(key1 -> 1, key2 -> 4, key3 -> 6, key5 -> 10)
合併map,相同key,value相加map
val map1 = Map("key1" -> 1, "key2" -> 3, "key3" -> 5) val map2 = Map("key2" -> 4, "key3" -> 6, "key5" -> 10) val mapAdd1 = map1 ++ map2.map(t => t._1 -> (t._2 + map1.getOrElse(t._1, 0))) println(mapAdd1)
結果co
Map(key1 -> 1, key2 -> 7, key3 -> 11, key5 -> 10)