Scala immutable map and list of tuples

What's the difference between an immutable map and a list of tuples in Scala? When should you use each of them? Which one is preferable if both are possible?

+3


source to share


2 answers


The two data structures are completely different.

1. Map

search time O(1)

. In the list it will beO(n)

Therefore, if you need to search for items in your key value, use Map

.

scala> val myMap = Map("a" -> 1, "b" -> 2, "c" -> 3)
myMap: scala.collection.immutable.Map[String,Int] = Map(a -> 1, b -> 2, c -> 3)

scala> myMap.get("a")
res7: Option[Int] = Some(1)

scala> myMap.getOrElse("a", 0)
res8: Int = 1

scala> myMap("a")
res9: Int = 1

      

As others have pointed out, there are two other major differences:



2.Keys in Map

must be unique

scala> val myList = List(("a", 1), ("b", 2), ("a", 3))
myList: List[(String, Int)] = List((a,1), (b,2), (a,3))

scala> myList.toMap
res0: scala.collection.immutable.Map[String,Int] = Map(a -> 3, b -> 2)

      

3. Map

is an unordered

scala> Map("a" -> 1, "b" -> 2, "c" -> 3, "d" -> 4, "e" -> 5).toList
res2: List[(String, Int)] = List((e,5), (a,1), (b,2), (c,3), (d,4))

      

+5


source


I would disagree (with @Akavall) that the two data structures are completely different. They are both a sequence (or a list in this case) of key-value pairs. In this sense, they are completely homologous. They have different behaviors such as the search performance that @Akavall mentions. However, this performance only applies to a Map that is implemented as a HashMap (or something similar). This aspect of behavior is not determined by the Card itself. However, there is another difference with Maps. Typically, the key values ​​on the map are different (see definition in Associative Array ).



I would suggest that each has its own capabilities. The [K, V] map is best if you are sure the keys will be unique and require a quick lookup. Seq [(K, V)] is best when you have no requirement to do fast searches (or perhaps you know you might want to search in any direction, i.e. from K-> V or from V-> K ) or when you expect keys to be duplicated. Often in Scala, a Map is built from a sequence of sets.

+4


source







All Articles