[SalesForce] Better way to use Map of List

I have a map of Id to List of Sobject. To update the map i use below code snippet

for(SObject so : listSObject) {
    if(mapSO.get(so.ParentId) != NULL)
        mapSO.get(so.PartentId).add(so);
    else
        mapSo.put(so.ParentId,new List<SObject>{so});
}

I came across a code like this

for(SObject so : listSObject) { 
    List<SObject> lstSO = new List<SObject>();
    if(mapSO.containsKey(so.ParentId))
        lstSO = mapSO.get(so.PartentId);
    lstSO.add(so);
    mapSo.put(so.ParentId,lstSO);
}

My question is which is the best way to use? What are the advantages over one another? Any performance related differences?

Best Answer

Here is another common way to accomplish this:

for (SObject so : listSObject) {
    List<SObject> listSo = mapSO.get(so.PartentId);
    if (listSo == null) {
        listSo = new List<SObject>();
        mapSo.put(so.PartentId, listSo);
    }
    listSo.add(so);
}

Working code is what matters, but I'll mention that this does a single get rather than a contains and then a get (in the common case of the list already being in the map) so if the map key lookup is expensive (with a normal hash map first the hashCode has to be converted to a bucket index then the list at that index searched for the key by invoking equals on each entry) that may help performance.

Related Topic