Trying to create a method to return a Map of SObjects using any field I want (not Id or I would use the Map constructor that takes a List).
private static Map<String, SObject> getSObjectMap(List<SObject> records, String fieldName) {
String sObjectTypeString = String.valueOf(records[0].getSObjectType());
Type t = Type.forName('Map<String,' + sObjectTypeString + '>');
Map<String, SObject> mapRecords = (Map<String, SObject>) t.newInstance();
for (SObject record: records) {
String key = (String) record.get(fieldName);
mapRecords.put(key, record);
}
return mapRecords;
}
REVISED (per Derek F) Map variable name from "map" to "mapRecords" to resolve "Unexpected token: Map" and "Expecting ';' but was ','" and "Unexpected token: map" for the second line.