You need to sign in to do that
Don't have an account?
BrianH
Best way to combine lists of contacts
What would the best way to combine 4 separate lists into 1 in this scenario? (These lists all contain contact objects.)
List1 - Contact ID and Field1
List2 - Contact ID and Field2
List3 - Contact ID and FIeld3
List4 - Contact ID and FIeld4
I would then need List5 to contain all contacts from Lists1-4 in with all fields.
List5 - Contact ID, Field1, Field2, Field3, Field4
Ok now i got your problem. now there are two solutions for your problem.
1) Use merge : This will only work if your list size is very less, other wise dml limit will exceed. This is not the best way to do it. Please check contact is mergable before going for this solution. I think it is.
2)
Step 1 : Create a map from first all four lists for unique items and remove them from original list.
Step 2 : If any item comes again already existing in map then check for all the fields on contact, if any field is empty then copyfield value from the list item to map item. You will have to use sObject methods for this
if(sObjectFromMap.get(FieldAPIName) == null)
sObject.put(FieldAPIName , sObjectDuplicate.get(FieldAPIName))
Repeat this on all lists, your map will have unique items with all the values.
All Answers
Use this
List Method : addAll ,
Addall doesn't quite do what I need. Using that method, if List1 and List2 contained the same contact, that contact would be in List5 twice. I need the contacts to be merged if they exist in multiple lists.
In this case create a
Set<Contact> setUniqueCon = new Set<Contact>();
setUniqueCon.addAll(list1);
setUniqueCon.addAll(list2);
setUniqueCon.addAll(list3);
setUniqueCon.addAll(list4);
You can use this set or you can copy this to your list5
list5.addall(setUniqueCon);
That's still not quite what I need.
If List1 contains a contact and List2 contains the same contact but with different fields, then it still gets added to the set as a separate item.
What I need to happen is as follows.
List1
List2
My result needs to be:
List3
Ok now i got your problem. now there are two solutions for your problem.
1) Use merge : This will only work if your list size is very less, other wise dml limit will exceed. This is not the best way to do it. Please check contact is mergable before going for this solution. I think it is.
2)
Step 1 : Create a map from first all four lists for unique items and remove them from original list.
Step 2 : If any item comes again already existing in map then check for all the fields on contact, if any field is empty then copyfield value from the list item to map item. You will have to use sObject methods for this
if(sObjectFromMap.get(FieldAPIName) == null)
sObject.put(FieldAPIName , sObjectDuplicate.get(FieldAPIName))
Repeat this on all lists, your map will have unique items with all the values.