[SalesForce] Collection of List keyed by sObject field

Is it possible to have a Map (or other collection) of sObjects list, keyed by one lookup field of the same sObject.

Something like Maps of sObjects (below code doesn't works):

Map<Id, List<Custom__c>> itemsMap = new Map<Id, List<Custom__c>>([SELECT Lookup_To_Custom__r.Id, Name FROM Custom__c]);

Note: this gives the following error Invalid initial type LIST<Custom__c> for MAP<Id,LIST<Custom__c>>

Were the Idin Map<Id, List<Custom__c>> is a reference to the Lookup_To_Custom__r.Id field.

Best Answer

The special map constructor only handles the case of creating a map where the key is the ID and the value is the SObject.

To do what I think you want to do requires a loop:

Map<Id, List<Custom__c>> m = new  Map<Id, List<Custom__c>>();
for (Custom__c c : [
        SELECT Lookup_To_Custom__c, Id, Name
        FROM Custom__c
        WHERE Lookup_To_Custom__c != null
        ORDER BY Name
        ]) {
    List<Custom__c> l = m.get(c.Lookup_To_Custom__c);
    if (l == null) {
        l = new List<Custom__c>();
        m.put(c.Lookup_To_Custom__c, l);
    }
    l.add(c);
}

Note that using the foreign key field Lookup_To_Custom__c is a little more direct than going through the reference and taking the ID Lookup_To_Custom__r.Id.