[SalesForce] How to define a map with id and list of records

I need to store it in a map with List as child and Id as parent

For an example my data spit something like this just to give you an idea:

DEBUG|//PId :  500o0000008V0alBAC
DEBUG|//Child: CaseNumber: 12345A Status: Not Started

DEBUG|//PId :  500o0000008V0alBAC
DEBUG|//Child: CaseNumber: 12345B Status: Not Started

DEBUG|//PId :  500o0000008V0alBAC
DEBUG|//Child: CaseNumber: 12345C Status: Not Started

DEBUG|//PId :  500o0000008V0alBAC
DEBUG|//Child: CaseNumber: 12345D Status: Not Started 

//many more different Pid and Child ....

How can I store that in Map?, something like this?

 Map<Id, List<Case>> parentChildCase = new map<Id, List<Case>>();

Here is my code that render the above debug code:

Map<id, id> pcids = new Map<id, id>(); 
//....

for(Case c :[/*SOQL*/]) {
   if(pcids.containskey(c.ParentId) {
     system.debug('//Pid: ' + parents.get(c.pareintid));
     system.debug('Child: ' + c);
   }
}

Best Answer

If i'm understanding this correctly you have a Case, and that case can have any number of cases under it. So you need a Map<ID, List<Case>>, this is how I would solve that.

Map<Id, List<Case>> parentChildCase = new Map<Id, List<Case>>();
Map<ID, Case> cMap = new Map<ID, Case>([SELECT Id, ..., FROM Case]);

for(ID c : cMap.keySet()) 
{
    if(parentChildCase.containsKey(cMap.get(c).ID)) 
    {
        parentChildCase.get(cMap.get(c).ID).add(cMap.get(c));
    }
    else
    {
        List<Case> cases = new List<Case>();
        cases.add(cMap.get(c));
        parentChildCase.put(cMap.get(c).ID, cases);
    }
}   
Related Topic