Skip to content

Instantly share code, notes, and snippets.

@bmodeprogrammer
Created February 19, 2021 23:16
Show Gist options
  • Save bmodeprogrammer/39063dd9a0e69a145be37144d992762b to your computer and use it in GitHub Desktop.
Save bmodeprogrammer/39063dd9a0e69a145be37144d992762b to your computer and use it in GitHub Desktop.
From a list of SObject and a field Api Name returns a Map with a list of SObject per field value
/*
* Example: Get a map of list of contacts by status from list of contacts
* @param: List<SObject> objects
* @param: String fieldName - field Api Name of a text field
* @return Map<String, List<SObject>> sObjectListByString
*/
public static Map<String, List<SObject>> getSObjectListByString(List<SObject> objectList, String fieldName) {
Map<String, List<SObject>> sObjectListByString = new Map<String, List<SObject>>();
String fieldValue;
for (SObject obj: objectList) {
fieldValue = (String) obj.get(fieldName);
if (sObjectListByString.containsKey(fieldName)) {
sObjectListByString.put(fieldValue, new List<SObject>());
}
sObjectListByString.get(fieldValue).add(obj);
}
return sObjectListByString;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment