Scala:将 Map[K,V] 转换为 IntMap[V] 最有效的方法是什么?
假设我有一个带有 toInt
方法的 Point 类,并且对于某些类型 V
有一个不可变的 Map[Point,V]
>. Scala 中将其转换为 IntMap[V]
的最有效方法是什么?这是我当前的实现:
def pointMap2IntMap[T](points: Map[Point,T]): IntMap[T] = {
var result: IntMap[T] = IntMap.empty[T]
for(t <- points) {
result += (t._1.toInt, t._2)
}
result
}
[编辑] 我的意思主要是更快,但我也会对较短的版本感兴趣,即使它们不是明显更快。
Let"s say I have a class Point with a toInt
method, and I have an immutable Map[Point,V]
, for some type V
. What is the most efficient way in Scala to convert it to an IntMap[V]
? Here is my current implementation:
def pointMap2IntMap[T](points: Map[Point,T]): IntMap[T] = {
var result: IntMap[T] = IntMap.empty[T]
for(t <- points) {
result += (t._1.toInt, t._2)
}
result
}
[EDIT] I meant primarily faster, but I would also be interested in shorter versions, even if they are not obviously faster.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
IntMap
为此有一个内置工厂方法 (apply
):如果速度是一个问题,您可以使用:
IntMap
has a built-in factory method (apply
) for this:If speed is an issue, you may use:
一个使用
breakOut
获取IntMap
的单行代码。它使用breakOut
调用解析的自定义构建器工厂CanBuildFrom
映射到新集合:就性能而言,很难告诉,但它创建一个新的
IntMap
,遍历所有绑定并将它们添加到IntMap
中。手写迭代器while
循环(前面有模式匹配以检查源映射是否是IntMap
)可能会带来更好的性能。A one liner that uses
breakOut
to obtain anIntMap
. It does amap
to a new collection, using a custom builder factoryCanBuildFrom
which thebreakOut
call resolves:In terms of performance, it's hard to tell, but it creates a new
IntMap
, goes through all the bindings and adds them to theIntMap
. A handwritten iteratorwhile
loop (preceded with a pattern match to check if the source map is anIntMap
) would possibly result in somewhat better performance.