Play Games

Search This Blog

Monday, July 11, 2022

Convert list into map in salesforce - Salesforce Globe For You

Solution: In order to convert list into map in salesforce, iterate the list and use the map.get() and map.put() to prepare the map

Example: In this example we will create map with AccountId as key and value as list of contacts by iterating the list of contacts

Map<String,List<contact>> mapAccountWithContacts = new Map<String,List<Contact>>();

for(contact objContact :[Select id,name,accountId from contact where accountId != null]) {

if(mapAccountWithContacts.containsKey(objContact.accountId)) {

mapAccountWithContacts.get(objContact.accountId).add(objContact);

} else {

mapAccountWithContacts.put(objContact.accountId,new List<Contact>{objContact});

}

}

system.debug('Map :'+mapAccountWithContacts);

Output:



No comments:

Post a Comment