7.3 Introducing Map

The concept

Map can be considered as a collection of Key-Value pairs. It is like, for each word in dictionary, there is a page number associated with it. Let’s suppose one page can only accommodate one particular word. And that is pretty much what map is.

In Map, the key and value can both be any type. But it is a good practice to keep the keep as a primitive type. The keys must be unique. They are always stored in pairs.

Map<String, Integer> wordDictionary = new Map<String, Integer>();
wordDictionary.put('Hello', 1);
wordDictionary.put('World', 2);
wordDictionary.put('Salesforce', 100);
wordDictionary.put('sfdcinpractice.com', 150);

for(String keyWord: wordDictionary.keySet()) 
    System.debug('The word ' + keyWord + ' is on Page ' + wordDictionary.get(keyWord));

The result should look similar to below:

A bit explanation

In the code above, we have seen some methods of Map. First, a map’s full type is categorised by its key and value’s type. And we can use put to add more key/value pairs into it. We can use get to fetch the value using a specified key. And finally, keySet returns a set of all the available keys in current map. To view the whole list of methods available for map, you can refer to here.


Write another map using numbers as keys and strings as values. Try to use it.

Next Post

7.4 Nested usage of Map and List

Subscribe to Sfdcinpractice

Subscribe to get the latest blogs and tutorials of sfdcinpractice. No spam, no trash, only the awesome posts from sfdcinpractice. 

Leave a Reply

Your email address will not be published / Required fields are marked *