Map with one key and multiple values in Salesforce APEX

You are currently viewing Map with one key and multiple values in Salesforce APEX
map with one key and multiple values in apex

Suppose that you have an scenario where you want map of records with one key and multiple values for single key. let’s see how we can achieve that in APEX.

To achieve this we have to create the map of <String , List> , where String is key and List will have list of values. See the syntax given below

				
					Map<String,List<String>> Countries = new  Map<String,List<String>>();  
				
			

Here we have create the countries map . Now let’s create a List for states.

				
					List<String> india = new List<String>();
india.add('Goa');
india.add('Punjab');
				
			

Now let’s add this List of states to the Countries map .

				
					Countries.put('India',india);
				
			

Now with the help of key we can access all the values at a time.

				
					System.debug(Countries.get('India'));
				
			

Le’s recap what we have did , here is the complete code for you .

				
					Map<String,List<String>> Countries = new  Map<String,List<String>>();  
    
List<String> india = new List<String>();
india.add('Goa');
india.add('Punjab');

Countries.put('India',india);
System.debug(Countries.get('India'));

				
			

This is how we can add multiple values for one key in map using apex . If you have another way to solve this problem then please share .

Thank you.

Leave a Reply