Maps
Maps are the second kind of collections available in Sonar. Similarly to the dictionary of Python, the hash of Ruby and the object-map of JavaScript, Sonar's map allows you to store data as a collection of key-value pairs. Each value can be retrieved if you know its key, much like a door can be unlocked if you have its key, or your iPhone can be unlocked if you have the right passcode.
More correctly, maps in Sonar collections of key-value pairs, arranged so that each key only appears once. In other words, maps emulate a one-to-one mapping relationship.
Maps are most useful when it is necessary to store a collection of values using a value other than their index (or position).
Maps Work Like Dictionaries
Maps follow the same principle as dictionaries (and thesauri, and all other reference books like catalogues and phonebooks). In fact, using a map, one can write a phonebook pretty easily, as we will see.
Map keys can be strings, numbers (integers and floats), and booleans. These datatypes are called hashables. Non-hashable types like arrays and other maps cannot be used as map keys.
Creating a Map
Creating a map is incredibly easy using the map operator ({}).
You can create a map with data in it from the beginning:
Accessing Map Values
Similar to Arrays, we can access specific map values using the accessor operator, provided we know the corresponding key.
Values can also be changed:
New keys can be created with values:
Removing Keys/Values from Maps
A key-value pair can be deleted from a map with the minus (-) operator.
It is important to remember that this operation will change the original map. If you need to retain the key in the original map, you will need to make a copy of the map first.
copy() can be used with every data type.
With all we have learned so far, we can create a phonebook program very easily:
Maps are also called "associative arrays". Can you find out why?
Last updated