MapValues和Map中的变换之间的区别 [英] Difference between mapValues and transform in Map
问题描述
在Scala 地图
(请参阅 API ) mapValues
和 transform $之间的语义和性能有什么区别? c $ c>?
In Scala Map
(see API) what is the difference in semantics and performance between mapValues
and transform
?
对于任何给定的地图,例如
For any given map, for instance
val m = Map( "a" -> 2, "b" -> 3 )
m.mapValues(_ * 5)
m.transform( (k,v) => v * 5 )
提供相同的结果。
推荐答案
我们假设我们有一个地图[A,B]
。澄清:我一直指的是一个不变的地图
。
Let's say we have a Map[A,B]
. For clarification: I'm always referring to an immutable Map
.
mapValues
采用函数
B => C
,其中 C
是值的新类型。
mapValues
takes a function B => C
, where C
is the new type for the values.
transform
需要一个函数(A,B)=> C
,其中 C
也是值的类型。
transform
takes a function (A, B) => C
, where this C
is also the type for the values.
所以将导致映射[A,C]
。
但是,使用 / code>函数,您可以通过其键值来影响新值的结果。
However with the transform
function you can influence the result of the new values by the value of their keys.
例如:
val m = Map( "a" -> 2, "b" -> 3 )
m.transform((key, value) => key + value) //Map[String, String](a -> a2, b -> b3)
使用 mapValues
执行此操作将相当困难。
Doing this with mapValues
will be quite hard.
接下来的区别是 transform
是严格的,而 mapValues
只会给你一个视图,不会存储更新的元素。看起来像这样:
The next difference is that transform
is strict, whereas mapValues
will give you only a view, which will not store the updated elements. It looks like this:
protected class MappedValues[C](f: B => C) extends AbstractMap[A, C] with DefaultMap[A, C] {
override def foreach[D](g: ((A, C)) => D): Unit = for ((k, v) <- self) g((k, f(v)))
def iterator = for ((k, v) <- self.iterator) yield (k, f(v))
override def size = self.size
override def contains(key: A) = self.contains(key)
def get(key: A) = self.get(key).map(f)
}
(取自 https://github.com/scala/scala/blob/v2.11.2/src/library/scala/collection/MapLike .scala#L244 )
所以性能方面取决于什么是更有效。如果 f
是昂贵的,您只能访问生成的地图的几个元素, mapValues
可能会更好,因为 f
仅适用于需求。否则我会坚持 map
或 transform
。
So performance-wise it depends what is more effective. If f
is expensive and you only access a few elements of the resulting map, mapValues
might be better, since f
is only applied on demand. Otherwise I would stick to map
or transform
.
transform
也可以用 map
表示。假设 m:映射[A,B]
和 f:(A,B)=> C
,然后
transform
can also be expressed with map
. Assume m: Map[A,B]
and f: (A,B) => C
, then
m.transform(f)
相当于 m.map {case(a,b)=> (a,f(a,b))}
这篇关于MapValues和Map中的变换之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!