Yet another update to the AnotherBoringUtilClass.

This time it’s to extract a Set of fields from a list of objects.  I find myself writing the same loop over and over to do this work – often in a trigger or another bulkification scenario.  The idea is that this method will take a list of objects and return you a set of the values associated with one particular field in that object.  So for example; here’s a list of contacts, return me a set of all of the AccountIds they’re related to. This set can then be used to query the accounts in one nice quick SOQL statement; yes I know I’m teaching you all things you already know – send me your Grandmother’s address if you’re offended.


public static Set<Object> extractFieldValues(List<sObject> input, String fieldName){

    Set<Object> output = new Set<Object>();

    for(sObject obj : input){
        output.add(obj.get(fieldName))<wbr>;</wbr>
    }

    return output;

}

And you could use it in a trigger like so:


trigger DoSomethingSilly on Contact (after insert){

    Set<Id> accountIds = AnotherBoringUtilClass.<wbr>extractFieldValues(Trigger.<wbr>new, 'AccountId');</wbr></wbr>
    List<Account> accs = [SELECT Id, NumberOfEmployees FROM Account WHERE Id IN :accountIds];

    for(Account acc : accs){
        acc.NumberOfEmployees += 1;
    }

    update accs;

}