C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Get: To get a value from a key in the "colors" map, we access the colors like a function. We pass the key as the argument.
Scala program that creates Map
// Use simple map initialization syntax.
val weights = Map("cat" -> 10, "elephant" -> 200000)
// Look up animal weights.
val weight = weights("elephant")
println(weight)
Output
200000
Scala program that creates Map with pair syntax
// Create map of animals to colors.
// ... Has string keys and string values.
val colors = Map(("bird", "blue"), ("fox", "red"))
// Get value for this key.
val result1 = colors("bird")
println(result1)
val result2 = colors("fox")
println(result2)
Output
blue
red
Scala program that adds key, value to map
// Create an immutable map.
val zoo = Map("frog" -> 1, "lion" -> 1)
// Add a pair to the map.
// ... This creates a new map.
val all = zoo + ("zebra" -> 1)
println(all)
Output
Map(frog -> 1, lion -> 1, zebra -> 1)
Keys: We use the foreach function on the keys collection (which is an iterable) and use println on each key.
Values: Here we use an imperative for-loop to call println on each value in the Map.
ForScala program that gets keys, values
// Create map of String keys and Int values.
val ids = Map(("abc", 10), ("def", 20))
// Use foreach function to print each key.
ids.keys.foreach(println(_))
// Use for-loop to iterate over all values.
for (value <- ids.values) {
println(value)
}
Output
abc
def
10
20
Get: This returns an option, not the value type of the Map. We must always test the option.
GetOrElse: This lets us provide a default value that is returned if the key does not exist in the Map. Here we use 0 as a default.
Scala program that uses get, getOrElse
// Create a String, Int map.
val sizes = Map(("Medium", 2), ("Large", 4))
// This key does not exist, so the option is not defined.
val result1 = sizes.get("Small")
if (!result1.isDefined) {
println("Not defined")
}
// This key exists.
// ... Get and print the option's internal value.
val result2 = sizes.get("Large")
if (result2.isDefined) {
println(result2)
val number = result2.get
println(number)
}
// Use a default value if the key does not exist.
val result3 = sizes.getOrElse("Small", 0)
if (result3 == 0) {
println("Zero, else value")
}
Output
Not defined
Some(4)
4
Zero, else value
Here: We find map1 and map2 are equal because their key-value pairs are the same. But map3 has a different value so it is not equal.
Scala program that uses equals
// Create three maps.
// ... The first two are equal but have different orders.
// The third one has different entries.
val map1 = Map((10, true), (20, false))
val map2 = Map((20, false), (10, true))
val map3 = Map((20, true), (10, true))
// These two maps are structurally equal.
if (map1.equals(map2)) {
println("Maps equal")
}
// Not equal.
if (!map1.equals(map3)) {
println("Maps not equal")
}
Output
Maps equal
Maps not equal
So: When we do a lookup on the map that does not find an existing key, the default value is returned.
WithDefault: This method returns a default value based on a function. We can pass a lambda expression to the withDefault method.
Here: The map does not contain the key "bear" so the final look up in the program returns the value -1.
Scala program that uses withDefaultValue
val animalMap = Map(("cat", 10), ("bird", 5))
// The default value is now negative 1.
val animalMapDefault = animalMap.withDefaultValue(-1);
// Use map with default.
val result1 = animalMapDefault("cat")
println(result1)
val result2 = animalMapDefault("bear")
println(result2)
Output
10
-1
Version 1: In this version of the code we search the Map with a string argument. We repeat this operation in a for-loop.
Version 2: Here we try to find the element in a List. We use a for-loop to search. The operation is repeated many times.
ListResult: Finding element "c" in the Map is faster than in the List. The fast lookup time helps this benchmark.
Scala program that times Map and List
// Map and list used.
val lookup = Map(("a", 1), ("b", 1), ("c", 1))
val list = List("a", "b", "c")
var total = 0
val t1 = System.currentTimeMillis()
// Version 1: look up element in a map.
for (i <- 0 until 10000000) {
val result = lookup("c")
total += result
}
val t2 = System.currentTimeMillis()
// Version 2: search for element in a list.
for (i <- 0 until 10000000) {
var result = 0
for (v <- list) {
if (v == "c") {
result = 1
}
}
total += result
}
val t3 = System.currentTimeMillis()
// Results.
println(total)
println(t2 - t1)
println(t3 - t2)
Output
20000000
77 ms, Map
140 ms, List
Note: For this Map, elements cannot be added, but new maps can be created. We add elements by creating new maps.
Quote: A generic trait for immutable maps. Concrete classes have to provide functionality for the abstract methods in Map (Scala Standard Library).