简体   繁体   中英

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

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.

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

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

If speed is an issue, you may use:

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

A one liner that uses breakOut to obtain an IntMap . It does a map to a new collection, using a custom builder factory CanBuildFrom which the breakOut call resolves:

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

In terms of performance, it's hard to tell, but it creates a new IntMap , goes through all the bindings and adds them to the IntMap . A handwritten iterator while loop (preceded with a pattern match to check if the source map is an IntMap ) would possibly result in somewhat better performance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM