Scala's MapLike
trait has a method
mapValues [C] (f: (B) ⇒ C): Map[A, C]
But I sometimes want a different type:
mapKeysAndValues [C] (f: (A, B) ⇒ C): Map[A, C]
Is there a simple way to do this which I am missing? Of course, this can be done with a fold.
Scala map is a collection of key/value pairs. Any value can be retrieved based on its key. Keys are unique in the Map, but values need not be unique. Maps are also called Hash tables.
Scala map contains() method with example It checks whether the stated map contains a binding for a key or not. Where, k is the key. Return Type: It returns true if there is a binding for the key in the map stated else returns false.
We can insert new key-value pairs in a mutable map using += operator followed by new pairs to be added or updated.
Scala Map is a collection of Key-value pair. A map cannot have duplicate keys but different keys can have same values i.e keys are unique whereas values can be duplicate.
map
method iterates though all (key, value)
pairs. You can use it like this:
val m = Map("a" -> 1, "b" -> 2)
val incM = m map {case (key, value) => (key, value + 1)}
What about this code:
val m = Map(1 -> "one", 2 -> "two")
def f(k: Int, v: String) = k + "-" + v
m map {case (k, v) => (k, f(k, v))}
Which produces:
Map(1 -> 1-one, 2 -> 2-two)
This can be packaged into utility method:
def mapKeysAndValues[A,B,C](input: Map[A,B], fun: (A, B) => C) =
input map {case(k,v) => (k, fun(k, v))}
Usage:
mapKeysAndValues(
Map(1 -> "one", 2 -> "two"),
(k: Int, v: String) => k + "-" + v
)
m map (t => (t._1, t._2 + 1))
m map (t => t._1 -> t._2 + 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