function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Omi DeshmaneOmi Deshmane 

how to compare two list in apex class

I have Two List of object records.
List<Account> accList1 = {1st record, 2nd record, 3rd record, 4th record};
List<Account> accList2 = {1st record, 3rd record};
 
I have another List<Account> accList3 = new List<Account>()
now I want to compare both List list1 and list2, get the record from list1 which is not present in list2 and add to List3.
 
Best Answer chosen by Omi Deshmane
edralphedralph
//assuming that accList1 and accList2 already exist...
List<Account> accList3 = new List<Account>();

for(Account acc1:accList1) { //for each account in accList1...
  if(!accList2.contains(acc1)) accList3.add(acc1); //if list2 does not contain the item from list1, add it to list3
}

//do whatever with accList3

Something like this would work.

All Answers

edralphedralph
//assuming that accList1 and accList2 already exist...
List<Account> accList3 = new List<Account>();

for(Account acc1:accList1) { //for each account in accList1...
  if(!accList2.contains(acc1)) accList3.add(acc1); //if list2 does not contain the item from list1, add it to list3
}

//do whatever with accList3

Something like this would work.
This was selected as the best answer
Malika Pathak 9Malika Pathak 9

Hi OM Deshmane,

please find the below solution

List<Account> accList=new List<Account>();
accList=[SELECT Id from Account LIMIT 2];
List<Account> accList2=new LIst<Account>();
accList2=[SELECT Id from Account LIMIT 3];
List<Account> accList3=new List<Account>();
Map<Id,Account> accMap=new Map<Id,Account>(accList);
Map<Id,Account> accMap1=new Map<Id,Account>(accList2);
system.debug('accMap==>'+accMap);
system.debug('accMap1==>'+accMap1);
if(accMap.keySet().size()>=accMap1.keySet().size()){

for(Id idObj:accMap.keySet()){
if(!accMap1.containsKey(idObj)){
accList3.add(accMap.get(idObj));
}
}
system.debug('accList3in==>'+accList3);
}else{
for(Id idObj:accMap1.keySet()){
if(!accMap.containsKey(idObj)){
accList3.add(accMap1.get(idObj));
}
}
system.debug('accList3in1==>'+accList3);
}
if(accList3.size()>0){
system.debug('working');
system.debug('accList3==>'+accList3);
}

If you find this helpful mark it as the best answer.
Sandesh D GanjareSandesh D Ganjare
Hi Om,
Use nested for loop for comparing these Account records and use id as a unique key.
for(Account a : accList1){
     if(!accList2.contains(a)){
        accList3.add(a); 
 }
}
try this.
ref: http://peterknolle.com/apex-list-contains/
Omi DeshmaneOmi Deshmane
Thank You guys @edralph, @Malika and @Sandesh.
Its working.
Assam teerAssam teer
Nice information Juwai Teer (https://juwai.teernews.in/)
natasha khannatasha khan
Nice information about juwait teer, (https://teerpoint.com)Shillong (https://indiateerresult.blogspot.com).
https://indiateerresult.blogspot.com/