Friday, June 19, 2020

Display account related contacts using map in salesforce

Sample Code
map<String, list<Contact>> mapAccAndCons = new map<String, list<Contact>>();
list<Contact> lstCons = [Select Id, Name, Account.Name from Contact];

for(Contact conIterator : lstCons) {
    if(!mapAccAndCons.containsKey(conIterator.Name)) {
        mapAccAndCons.put(conIterator.Name, new list<Contact>{conIterator});
    }
    else {
        mapAccAndCons.get(conIterator.Name).add(conIterator);
    }
}

System.debug('mapAccAndCons => '+mapAccAndCons);

Output
 

No comments:

Post a Comment