You need to sign in to do that
Don't have an account?
pooja biswas
remove duplicates using Map
Hi
I have 2 lists which I want to compare and remove duplicates and insert the values into sobject.
Here is the code its working but I want to know if I can remove atleast one For Loop using Map function.
List<Account> accList1=new List<Account>();
Account acc1=new Account();
acc1.Name='Falcon1';
Account acc2=new Account();
acc2.Name='Falcon1';
Account acc3=new Account();
acc3.Name='Falcon2';
Account acc4=new Account();
acc4.Name='Falcon3';
accList1.add(acc1);
accList1.add(acc2);
accList1.add(acc3);
accList1.add(acc4);
accList1.sort();
Set<Account> mySet1 = new Set<Account>();
mySet1.addAll(accList1); //removes duplicates from list
List<Account> aList2=[select ID,Name from Account Limit 50000];
Set<Account> mySet2 = new Set<Account>();
mySet2.addAll(aList2); //removes duplicates from List
Set<Account> dupSet = new Set<Account>();
for(Account a1:mySet1)
{
for(Account a2:mySet2)
{
If (a1 == a2) //if there are duplicates then collect them in dupes SET
dupSet.add(a1);
}
}
mySet1.removeAll(dupSet); //remove duplicates from mySet1
aList2.clear();
aList2.addAll(mySet1);
Database.Insert(aList2,false);
I want to know if there is an elegant way of doing the above using Map.
Thanks
pooja
I have 2 lists which I want to compare and remove duplicates and insert the values into sobject.
Here is the code its working but I want to know if I can remove atleast one For Loop using Map function.
List<Account> accList1=new List<Account>();
Account acc1=new Account();
acc1.Name='Falcon1';
Account acc2=new Account();
acc2.Name='Falcon1';
Account acc3=new Account();
acc3.Name='Falcon2';
Account acc4=new Account();
acc4.Name='Falcon3';
accList1.add(acc1);
accList1.add(acc2);
accList1.add(acc3);
accList1.add(acc4);
accList1.sort();
Set<Account> mySet1 = new Set<Account>();
mySet1.addAll(accList1); //removes duplicates from list
List<Account> aList2=[select ID,Name from Account Limit 50000];
Set<Account> mySet2 = new Set<Account>();
mySet2.addAll(aList2); //removes duplicates from List
Set<Account> dupSet = new Set<Account>();
for(Account a1:mySet1)
{
for(Account a2:mySet2)
{
If (a1 == a2) //if there are duplicates then collect them in dupes SET
dupSet.add(a1);
}
}
mySet1.removeAll(dupSet); //remove duplicates from mySet1
aList2.clear();
aList2.addAll(mySet1);
Database.Insert(aList2,false);
I want to know if there is an elegant way of doing the above using Map.
Thanks
pooja
I have done few modification in your code to reduce for loop
Hope this help you.
Thanks
Shweta
All Answers
I have done few modification in your code to reduce for loop
Hope this help you.
Thanks
Shweta
Thanks. that worked very well.
Pooja