Manu Chadha
Manu Chadha

Reputation: 16747

How does map decide which value to pick if key is duplicated

I am trying the following code to learn map collection. I notice that if the 'key' is duplicated, 'map' picks on value. How does the compiler decide which value to pick?

//key 2 and 3 are duplicated and has different values
val m3 = Map((2->"1"), (2->"2"), (3->"3"), (3->'4'))
m3: scala.collection.immutable.Map[Int,Any] = Map(2 -> 2, 3 -> 4)

//why was "2" and '4' picked and not "1" and "3"

Upvotes: 0

Views: 111

Answers (1)

Guillaume
Guillaume

Reputation: 1286

It would use the latest insert into the Map (think about it as an equivalent of an UPSERT: update if the key exists or insert into the Map if it does not).

Upvotes: 3

Related Questions