7.4 Nested usage of Map and List

The concept

The elements in list, set or map doesn’t have to be a primitive type. It can be another list, set or map as well. Here I am gonna show you an example of having list of string as element in a map. Let’s see if we have real world dictionary, one page can have multiple words but one word can only belong to one page number. Here is the code:

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

Map<Integer, List<String>> pageToWordMap = new Map<Integer, List<String>>();
for(String curWord: wordDictionary.keySet())
{
    Integer curPage = wordDictionary.get(curWord);
    if(!pageToWordMap.containsKey(curPage)) 
    {
        pageToWordMap.put(curPage, new List<String>()); //We need to initialise the list
    }
    pageToWordMap.get(curPage).add(curWord); //pageToWordMap.get(curPage) is a list here
}

for(Integer curPage: pageToWordMap.keySet())
{
    System.debug('Page ' + curPage + ' contains:');
    System.debug(pageToWordMap.get(curPage));
}

The result should be similar to the following:
nestedmap

A bit explanation

This piece of code is relatively hard to follow.

First, the element of a map can be list, set or map. And if the element is a container type, for each one, it needs to get initialised.

In our previous code, when we go through the first loop, if the page number doesn’t exist in the current map, it means the related list is not initialised yet. So we need to initialise the list first. Then, regardless of whether it is a new list or a existing one, we add the related String into the list.

The final part which prints the related list out is pretty straight-forward. Take a little bit more time to go through the piece of code if you find it difficult.

Exercise

Create a list of list to represent a matrix of data. And print the two dimensional list out using for loop.

Next Post

You can continue reading more about Object Oriented Apex in next chapter. However, I would recommend you to starting learning using Apex in Salesforce platform now. As you are already ready for it. Come to this tutorial to build something actual in Salesforce! It is gonna to exciting!

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 *