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
case commentscase comments 

getting the difference between two lists

I have a trigger in place to insert a list into a custom object.  I first want to make sure there aren't any duplicates first before inserting.  So far I have an sObject list of what's going to be inserted and another sObject list of what's already there.  How can i find what the difference is between the two lists to insert?

For example, let's use the Account object.  If i have the following in a List
List1
Acme, San Francisco
Acme, Los Angeles
IBM, New York

List2
Acme, San Francisco
Acme, Los Angeles
Acme, New York
IBM, New York

Out of those two lists, how can I pull out only Acme, New York?
Caleb SidelCaleb Sidel
You'll have to create your own algorithm for it.

You might do something like (pseudo code)

Set<String> findDifferent(List<String> list1, List<String> list2)
{
 Set<String> differences = new Set<String>();
differences.addAll(list1);
for(String item : list2) //This assumes list2 doesn't not contain dupes, if it might then first convert it to a set
{
  if( !differences.add(item) ) //if add returns false it means the set did NOT change, which means is already contains the item
  {
     differences.remove(item) //if the item was already there then remove it, it's not different...
  }
  //else if the item was not found, add it to differences to be returned later

}

return differences
}


The above should work...but I haven't tried it. Good luck!


RishavRishav
you can do one thing assign the data from both of the list to "SET"(set don't contain the duplicate value) so you can work with that set. But if your requirement is like that you can only work with the LIST then later you can transfer the data from that set to one final list.

I think it's feasible solution .