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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With