In contrast to Set, Map may contain non-unique values. What it actually maps is a key which points to a value. Key may be a number or a strings, and it must be unique. Value on the other hand, may be anything from primitive to an object, array or function. What is important here is that keys are sorted by the insertion order.
Methods
Map must implement a bunch of methods which will let you operate on underlying data. It will mostly operate on keys, but there are functions which help you manage values as well.
- map.set(key, value): adds value under the given key
- map.get(key): returns value by the key
- map.has(key): tells if a given key exists
- map.delete(key): removes key and all corresponding values from map
- map.clear(): removes all elements from map
- map.values(): returns all values in a form of an array
- map.keys(): returns all keys in a form of an array
- map.foreach(func): runs function func on every key->value pair within a map
Usages
Map allows for quick look-ups of values or objects, which are indexed by the key. It lets you cache elements which are expensive to calculate, a good example may be a Map of phone numbers mapped to people. Instead of searching name by the number in a huge database, you can index phones and quickly obtain corresponding person.