Another trick: how to obtain a set from any field in a list – faster and without loops!

This is like the previous post about getting maps out of a list, but with the same trick applied for getting a set.

In triggers, we usually code a loop like below to collect certain IDs in a set and later use the set in a query.

Set<String> acctIDSet = new Set<String>();
for( Contact aContact : ) {
    acctIDSet.add( aContact.AccountID );

The new SetCreator class does that without any loops and in a single line of code.

Set<String> acctIDSet =
      SetCreator.createSetFromField(, ‘AccountID’ );

Below is the definition of the SetCreator class that allows that.

public class SetCreator {
    public static Set<String> createSetFromField(
        List<SObject> aList, String fieldName ) {

    // get the list in JSON format
    String jsonList = JSON.serialize( aList );

    // copy only the fieldName value using RegEx substitution
    jsonList = jsonList.replaceAll(
        '(\\{.*?"' + fieldName + '":"(.*?)"(,".*?")*\\},?)'
        , ',"$2"' ).replace( '[,', '[' );

    // create set from the modified JSON
    Set<String> extractedSet =
        (Set<String>) JSON.deserialize(
            jsonList, Set<String>.class );

    return extractedSet;


It converts the list to a JSON string and modifies the string to look as if it was a serialized Set. It uses RegEx to keep the specified field values and remove everything else. It then deserializes the modified JSON string into a Set.
Again, there are no explicit loops – all of them are internal to the RegEx/JSON implementations, and are much faster.

Even if there are duplicates, they are automatically eliminated during the deserialization of the JSON string.



Posted on 12/30/2014, in No category. Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: