Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map both keys and values of a Scala Map

Tags:

scala

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.

like image 797
Alexey Romanov Avatar asked Feb 03 '12 14:02

Alexey Romanov


People also ask

Is a collection of keys or value pairs in scala?

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.

How do you check if a map contains a key in scala?

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.

How do you add a value to a map in scala?

We can insert new key-value pairs in a mutable map using += operator followed by new pairs to be added or updated.

Can map have duplicate keys scala?

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.


3 Answers

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)}
like image 188
tenshi Avatar answered Oct 10 '22 00:10

tenshi


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
)
like image 24
Tomasz Nurkiewicz Avatar answered Oct 10 '22 00:10

Tomasz Nurkiewicz


m map (t => (t._1, t._2 + 1))

m map (t => t._1 -> t._2 + 1)
like image 6
Grigory Kislin Avatar answered Oct 10 '22 01:10

Grigory Kislin