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 : trigger.new ) {
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( trigger.new, ‘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.