当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Scala HashMap.merged用法及代码示例


merged 方法(或属性)属于 scala.collection.immutable.HashMap 类(class),其相关用法说明如下。

用法:

def merged[V1 >: V](that: HashMap[K, V1])(mergef: ((K, V), (K, V1)) => (K, V1)): HashMap[K, V1]

通过组合两个映射的所有键值对并将这个HashMap 与另一个HashMap 合并,并委托给一个合并函数来解决两个 HashMap 之间的任何键冲突。

值参数:

mergef

解决两个 HashMap 之间冲突的合并函数。如果 mergef 为空,则来自 this 的键将覆盖来自 that 的键,使行为等同于 that.concat(this)

that

HashMap 将此 HashMap 与

注意:

如果 mergef 返回的键本身与 merge 返回的其他键发生冲突,或者在 thisthat 中找到,则未定义将选择哪个值.例如:碰撞多个合并结果:

// key `3` collides between a result of merging keys `1` and `2`
val left = HashMap(1 -> 1, 2 -> 2)
val right = HashMap(1 -> 1, 2 -> 2)
val merged = left.merged(right){ case (_, (_, v1)) => 3 -> v1 }
  // HashMap(3 -> 2) is returned, but it could also have returned HashMap(3 -> 1)

与其他键合并的碰撞结果:

// key `2` collides between a result of merging `1`, and existing key `2`
val left = HashMap(1 -> 1, 2 -> 1)
val right = HashMap(1 -> 2)
val merged = left.merged(right)((_,_) => 2 -> 3)
  // HashMap(2 -> 1) is returned, but it could also have returned HashMap(2 -> 3)

例子:

val left = HashMap(1 -> 1, 2 -> 1)
val right = HashMap(2 -> 2, 3 -> 2)
val merged = left.merged(right){ case ((k0, v0), (k1, v1)) => (k0 + k1) -> (v0 + v1) }
  // HashMap(1 -> 1, 3 -> 2, 4 -> 3)

源码:

HashMap.scala

相关用法


注:本文由纯净天空筛选整理自scala-lang.org大神的英文原创作品 HashMap.merged。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。