MapValues和Map中的变换之间的区别

编程入门 行业动态 更新时间:2024-10-21 11:57:31
本文介绍了MapValues和Map中的变换之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在Scala 地图(请参阅 API ) mapValues 和 transform ?

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) }

(取自 github/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中的变换之间的区别

本文发布于:2023-11-26 00:21:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631916.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:区别   MapValues   Map

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!