5

I have 2 lists of Contacts, which may both contain the same Contact(s) or they may not. I have a method that combines the lists, meaning if a Contact is in both lists it will take the Contact's properties of that one list and add those properties to the matching Contact in the other list and then add the Contact to one final list (finalContactUpdates). I am wondering if there is an easier way of doing it?

public static List<Contact> mergeContactLists(List<Contact> expiryDates, List<Contact> primaryCommunities) {
        List<Contact> finalContactUpdates = new List<Contact>();
        Map<Id, Contact> contactIdToContact = new Map<Id, Contact>();
        for(Contact con : expiryDates) {
            contactIdToContact.put(con.Id, con);
        }

        Map<Id, Contact> contactIdToContact2 = new Map<Id, Contact>();
        for(Contact con : primaryCommunities) {
            contactIdToContact2.put(con.Id, con);
        }

        for(Contact con : primaryCommunities) {
            if(contactIdToContact.keySet().contains(con.Id)) {
                //if a contact who's primaryCommunity changed also has an expiry date that changed, set the expiry date
                con.Membership_Expiry_Date__c = contactIdToContact.get(con.Id).Membership_Expiry_Date__c;
            }
            finalContactUpdates.add(con);
        }

        for(Contact con : expiryDates) {
            if(!contactIdToContact2.keySet().contains(con.Id)) {
                //if a contact's expiry date changed but primaryCommunity did not, add them to the contact list
                finalContactUpdates.add(con);
            }
        }
        return finalContactUpdates;
    }
9

Here's how'd I do it:

public static SObject[] mergeData(SObject[] list1, SObject[] list2) {
    Map<Id, SObject> results = new Map<Id, SObject>();
    for(SObject[] recordList: new List<SObject[]> { list2, list1 }) {
        for(SObject record: recordList) {
            results.put(record.Id, record.getSObjectType().newSobject(record.Id));
        }
    }
    for(SObject[] recordList: new List<SObject[]> { list2, list1 }) {
        for(Sobject record: recordList) {
            Map<String, Object> values = record.getPopulatedFieldsAsMap();
            SObject temp = results.get(record.Id);
            for(String field: values.keySet()) {
                temp.put(field, values.get(field));
            }
        }
    }
    SObject[] finalResults = list1.clone();
    finalResults.clear();
    finalResults.addAll(results.values());
    return finalResults;
}

This code builds a map of records, takes all the populated field values from both lists, merges them into a single record, and returns the results. Note that list1 and list2 should have the same data type, or Bad Things™ might happen.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.