You can use Map
in such kind of scenarios as well.
You can create a Map
with sObject
as key
with only the attributes which needs to be checked for duplication and value
as original sObject
. And when doing a check, create a new instance of sObject
with the same attributes and check if this instance is present in Map
, if it returns true
, that means its a duplicate else its not.
Map<Account, Account> mapAccounts = new Map<Account, Account>();
if(myList.size()>0){
List<Account> allAccounts = [SELECT Name,EMAIL,Company from Account];
for(Account acc : allAcounts){
//creating a map with key as sObject with fields Name, Company, Email and value as original Account sObject
Account keyAcc = new Account(Name = acc.Name, Company = acc.Company, Email = acc.Email);
mapAccounts.put(keyAcc,acc);
}
for(Account nl: myList){
Account valueToCheck = new Account(Name = nl.Name, Company = nl.Company, Email = nl.Email);
if(mapAccounts.containsKey(valueToCheck)){
dup.add(nl);
} else {
nondup.add(nl);
}
}
}
And a more traditional approach where you can create a unique key
by concatenating the values of the fields which needs to be used for duplication check i.e. in your case, it can be a combination of Name
Company
and Email
, so your key
of the Map
can be Name-Company-Email
and then you can check if the values with same combination exist in the map, if they exist, then they are duplicates else they are not duplicates.
So your code using this approach should be something like below
Map<string, Account> mapAccounts = new Map<string, Account>();
if(myList.size()>0){
List<Account> allAccounts = [SELECT Name,EMAIL,Company from Account];
string originalKey='';
string verificationKey='';
for(Account acc : allAcounts){
//creating a map with key as 'Name-Company-Email' and value as Account sObject
tempKey = string.valueOf(acc.Name!=null ? acc.Name : '' ) + '-' +
string.valueOf(acc.Company!=null ? acc.Company : '' ) + '-' +
string.valueOf(acc.EMAIL!=null ? acc.EMAIL : '' );
mapAccounts.put(tempKey, acc);
}
for(Account nl: myList){
verificationKey = string.valueOf(nl.Name!=null ? nl.Name : '' ) + '-' +
string.valueOf(nl.Company!=null ? nl.Company : '' ) + '-' +
string.valueOf(nl.EMAIL!=null ? nl.EMAIL : '' );
if(mapAccounts.containsKey(verificationKey)){
dup.add(nl);
} else {
nondup.add(nl);
}
}
}
The problem with your code is that you are looping the same records multiple times for various combination and due to this every time the condition doesn't match, it will go into the else
condition and add it as a non duplicate value. Although that can be avoided by using other techniques, but still I won't prefer that approach as it impacts the performance.