Saturday, April 20, 2013

Getting Unique Field Values for a List of Records

Here's a simple utility method that will return the set of values for a given field within a list of records. It's useful, for example, when you need to find all the Accounts referenced by a list of Contacts. Or to find the unique Status values used by a list of Cases.
/**
 * @description return the unique values for a given field in a list of 
 *  records. Null is not included.
 * @param objects the list of records
 * @param field values from this field will be returned
 * @return set of values; no null
 */
public static Set<String> getFieldValues(SObject[] objects, SObjectField field) {
  Set<String> result = new Set<String>();
  if (null != objects) {
    final String fieldName = field.getDescribe().getName();
    for (SObject o : objects) {
      result.add(String.valueOf(o.get(fieldName)));
    }
    result.remove(null);
  }

  return result;
}

And here's an easily-derived variation that saves you a little typing when getting the set of IDs from a list:
/**
 * @description return the unique Ids in a list of records.
 * @param objects the list of records
 * @return set of Ids; no null
 */
public static Set<String> getIds(SObject[] objects) {
  return getFieldValues(objects, Case.Id);
}

No comments:

Post a Comment