Home » Blog » Apex Snippet: Getting Unique Field Values for a List of Records

Apex Snippet: 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<Object> getFieldValues(SObject[] objects, SObjectField field) {
  Set<Object> result = new Set<Object>();
  if (null != objects) {
    for (SObject o : objects) {
      result.add(o.get(field));
    }
    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<Id> getIds(SObject[] objects) {
  return (Set<Id>)getFieldValues(objects, Case.Id);
}