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:

  1. a new, empty map created
  2. you map "abc" -> 1 3 -> 3 , add map. result contains 1 -> 3.
  3. you map "efg" -> 2 3 -> 2 , add map. since key same, overwrite existing value key = 3. result contains 2 -> 3.
  4. you map "hij" -> 3 3 -> 3 , add map. since key same, overwrite existing value key = 3. result contains 3 -> 3.
  5. 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

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -