dumm3rjung3
dumm3rjung3

Reputation: 129

scala: create map with keys from map.keys

I have a map, let's say:

m1:Map[String, Int] = Map(a -> 1, b -> 2, c -> 3, d -> 4)

and i now want to create a second map which has the same keys as the existing map and takes 0 as value for each key. So it should look like this:

m2:Map[String, Int] = Map(a -> 0, b -> 0, c -> 0, d -> 0)

I tried a for loop inside the map definition, but it didn't really work. How can I do that?

thanks!

Upvotes: 0

Views: 327

Answers (2)

raphaëλ
raphaëλ

Reputation: 6523

You could just mapValues:

 val m2 = m1.mapValues((v) -> 0)

EDIT: do read @elm's answer about the reference implications

Upvotes: 2

elm
elm

Reputation: 20405

To create a new map consider

m1.keys.map(k => (k,0)).toMap

and using a for comprehension,

for ( (k,v) <- m1 ) yield k -> 0

The approaches above create a new map. This is in contrast with the use of mapValues which creates a view to the original map and keeps the transformation function which is applied to the original map whenever queried. As far as the transformation function is referentially transparent, namely that it is not dependent on a context, this approach is sound. However, when a context the transformation function refers to, changes, the output from querying to the original map may also change. This is prevented with creating a new, transformed map.

Upvotes: 5

Related Questions