[SalesForce] How To Group Records By Value In A Specific Field

I have a List of records of type abc__c. abc__c is a custom object. The record has a field called code__c. What I am trying to accompolish is to group the records in the list based on the code__c.

For example the list might have :

Code__c     abc__c record
30       (Record 1)
40       (Record 2)
40       (Record 3)
50       (Record 4)
30       (Record 5)

I want to group these records based on Code__c in a Map. There could be any number of code__c which is populated dynamically. It is not static. how can I loop through the list and store the records as a list for a particular code__c(Id) in Map?

Best Answer

You can use a List as a Value for a Map.

Map<Integer, ABC__c[]> codeToABC = new Map<Integer, ABC__c[]>();
for(ABC__c record: abcRecords) {
    if(codeToABC.containsKey(record.Code__c)) {
        // Code already in map
        codeToABC.get(record.Code__c).add(record);
    } else {
        // Code is not yet in Map
        codeToABC.put(record.Code__c, new List<ABC__c> { record });
    }
}

You can swap out Integer for another data type (e.g. if Code is actually a String).

Related Topic