public class Domains{
public static void getuniqueDomain(List<Contact> conlist){
Set<String> domainNamesSet = new Set<String>();
Map<Id,Set<String>> AccIdAndEmailSetMap = new Map<Id,Set<String>>();
Set<Id> ParentAccountIdset = new Set<Id>();
List<Account> AccountsTobeUpdate = new List<Account>();
for(Contact con : conlist){
ParentAccountIdset.add(con.AccountId);
}
for(Account a : [SELECT Id,Domain_count__c,(SELECT Id,Email FROM Contacts) FROM Account WHERE Id IN: ParentAccountIdset]){
domainNamesSet.clear();
for(Contact c : a.Contacts){
if(c.Email!=null){
domainNamesSet.add(c.Email.Split('@').get(1));
}
}
AccIdAndEmailSetMap.put(a.Id,domainNamesSet);
}
for (Id key: AccIdAndEmailSetMap.keySet()) {
System.debug(LoggingLevel.DEBUG, 'key: ' + key + ' --> value: ' + AccIdAndEmailSetMap.get(key));
}
for(Id ids : AccIdAndEmailSetMap.keySet()){
Account a = new Account(Id=ids , Domain_count__c = AccIdAndEmailSetMap.get(ids).size());
AccountsTobeUpdate.add(a);
}
update AccountsTobeUpdate;
}
}
I'm calling this class in my trigger.