当前位置: 动力学知识库 > 问答 > 编程问答 >

collections - Why no mapKeys in Scala?

问题描述:

The Scala Collection library has mapValues and filterKeys. The reason it doesn't have mapKeys is likely the performance aspect (with regard to HashMap implementation), as discussed here for Haskell: Why there's not mapKeys in Data.Hashmap?

However.

Performance implications aside, I find myself needing mapKeys at least as much as mapValues, simply for massaging data (i.e. I'm using a map for data abstraction, not for its fetch speed).

Am I wrong, and which data model would you use for this? Tuples?

网友答案:

No idea why it's not in standard library, but you can easily pimp your library with implicit class

  implicit class MapFunctions[A, B](val map: Map[A, B]) extends AnyVal {
    def mapKeys[A1](f: A => A1): Map[A1, B] = map.map({ case (a, b) => (f(a), b) })
  }

  val m = Map(1 -> "aaa", 2 -> "bbb")

  println(m.mapKeys(_ + 1))
网友答案:

You can use scalaz:

import scalaz.Scalaz._

val m = Map(1 -> "aaa", 2 -> "bbb")
m.mapKeys(_ + 1)

In case of collisions the result may be smaller than the original Map.

分享给朋友:
您可能感兴趣的文章:
随机阅读: