Create a map for duplicate contacts by phone or email id


Dec 07, 2020    Janaki Mahapatra, Salesforce

Map<String,List> phoneMap = new Map<String, List>(); 
List scope = [SELECT Id,Phone,Email,CreatedDate FROM Contact WHERE (Phone!='' OR Email!='') 
order by createddate desc]; 
for(Contact ct:scope) { 
	String phone = String.valueOf(ct.Phone); 
	String email = String.valueOf(ct.Email); 
	if(String.isNotBlank(String.valueOf(ct.Phone))) { 
		phone = phone.replace('-', '').replace('(', '').replace(')', '').replace(' ', '').replace(',', ''); 
		if (phoneMap.containsKey(phone)) { 
			List c = phoneMap.get(phone); c.add(ct); 
		} else { 
			phoneMap.put(phone, new List{ ct }); 
		} 
	} else { 
		if (emailMap.containsKey(email)) { 
			List c = emailMap.get(email); c.add(ct); 
		} else { 
			emailMap.put(email, new List{ ct }); 
		} 
	} 
} 
for(String key:phoneMap.keySet()) { 
	List ct = phoneMap.get(key); 
	if(ct.size()>1) { 
		System.debug('phoneMap: ' + key + ': ' + ct.size() + ': ' + phoneMap.get(key)); 
	} 
} 
for(String key:emailMap.keySet()) { 
	List ct = emailMap.get(key); 
	if(ct.size()>1) { 
		System.debug('emailMap: ' + key + ': ' + ct.size() + ': ' + emailMap.get(key)); 
	} 
}