dictionary - Scala - map function - Only returned last element of a Map -
i new scala , trying out map function on map. here map:
scala> val map1 = map ("abc" -> 1, "efg" -> 2, "hij" -> 3) map1: scala.collection.immutable.map[string,int] = map(abc -> 1, efg -> 2, hij -> 3)
here map function , result:
scala> val result1 = map1.map(kv => (kv._1.touppercase, kv._2)) result1: scala.collection.immutable.map[string,int] = map(abc -> 1, efg -> 2, hij -> 3)
here map function , result:
scala> val result1 = map1.map(kv => (kv._1.length, kv._2)) result1: scala.collection.immutable.map[int,int] = map(3 -> 3)
the first map function returns members expected second map function returns last member of map. can explain why happening?
thanks in advance!
in scala, map
cannot have duplicate keys. when add new key -> value
pair map
, if key exists, overwrite previous value. if you're creating maps functional operations on collections, you're going end value corresponding last instance of each unique key. in example wrote, each string key of original map map1
has same length, , string keys produce same integer key 3
result1
. what's happening under hood calculate result1
is:
- a new, empty map created
- you map
"abc" -> 1
3 -> 3
, add map. result contains1 -> 3
. - you map
"efg" -> 2
3 -> 2
, add map. since key same, overwrite existing valuekey = 3
. result contains2 -> 3
. - you map
"hij" -> 3
3 -> 3
, add map. since key same, overwrite existing valuekey = 3
. result contains3 -> 3
. - return result,
map(3 -> 3
)`.
note: made simplifying assumption order of elements in map iterator same order wrote in declaration. order determined hash bin , not match order added elements, don't build relies on assumption.
Comments
Post a Comment