Scala - display function - returns only the last map element

I am new to Scala and tested the map function on the map. Here is my 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 is the map function and the 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 is another map function and 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 all members as expected, but the second map function returns only the last member of the map. Can someone explain why this is happening?

Thanks in advance!

+5
source share
1 answer

In Scala, a Map there can be no duplicate keys. When you add a new key -> value pair to Map , if that key already exists, you overwrite the previous value. If you create cards from functional operations on collections, you will end up with a value corresponding to the last instance of each unique key. In the example you wrote, each string key of the original map1 map has the same length, and so all your string keys produce the same integer key 3 for result1 . What happens under the hood to calculate result1 :

  • A new blank card is created.
  • Display "abc" -> 1 in 3 -> 3 and add it to the map. The result now contains 1 -> 3 .
  • You map "efg" -> 2 to 3 -> 2 and add it to the map. Since the key is the same, you are overwriting the existing value for key = 3 . The result now contains 2 -> 3 .
  • You map "hij" -> 3 to 3 -> 3 and add it to the map. Since the key is the same, you are overwriting the existing value for key = 3 . The result now contains 3 -> 3 .
  • Return the result that Map(3 -> 3 ) `.

Note. I made a simplified assumption that the order of the elements in the map iterator matches the order specified in the declaration. The order is determined by the hash bin and probably does not match the order in which elements are added, so don't build anything that relies on this assumption.

+8
source

Source: https://habr.com/ru/post/1259334/


All Articles