Scala: What is the most efficient way to convert a map [K, V] to IntMap [V]?

Say I have a Point class with the 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 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 primarily meant faster , but I was also interested in shorter versions, even if they are clearly not faster.

+4
source share
2 answers

IntMap has a built-in factory ( apply ) method for this:

 IntMap(points.map(p => (p._1.toInt, p._2)).toSeq: _*) 

If speed is a problem, you can use:

 points.foldLeft(IntMap.empty[T])((m, p) => m.updated(p._1.toInt, p._2)) 
+4
source

One liner that uses breakOut to get an IntMap . It creates a map for the new collection using the custom factory constructor CanBuildFrom , which enables the breakOut call:

 Map[Int, String](1 -> "").map(kv => kv)(breakOut[Map[Int, String], (Int, String), immutable.IntMap[String]]) 

In terms of performance, it's hard to say, but it creates a new IntMap , goes through all the bindings and adds them to IntMap . A handwritten iterator while (preceded by a pattern match to check if the original IntMap map is) may lead to slightly better performance.

+1
source

Source: https://habr.com/ru/post/1342493/


All Articles