[SalesForce] Get null values from map

//map to store attachments against categories
        for(MyDocument__c mdobj :[SELECT id,Category__c FROM MyDocument__c where id =:accObj.id]){

            for(Attachment attobj :[SELECT Id, Name, Description FROM Attachment WHERE ParentId = :mdobj.Id]){
                if(!catAttMap.containsKey(mdobj.category__c)){
                catAttMap.put(mdobj.Category__c, new list<Attachment>());
                }
                catAttMap.get(mdobj.Category__c).add(attobj);    
            }
        }

        system.debug('aaaaaaaaaaaaaaaaaaaaaa'+ catAttMap);

Best Answer

I think this would be more optimized solution:

for(MyDocument__c mdobj :[SELECT id,Category__c,(SELECT Id, Name, Description FROM Attachment) FROM MyDocument__c where id =:accObj.id]){

    if(!catAttMap.containsKey(mdobj.category__c)){
        if(mdObj.attachments.size()>0){
            catAttMap.get(mdobj.Category__c).add(mdobj.attachments);    
        }
        else{
            catAttMap.put(mdobj.Category__c, new list<Attachment>());
        }
    }
}

Here i have removed your query on attachment object.Instead i am doing it inside the parent query as inner query.

Now i can access all the related child of given custom object record by mdobj.attachments.Then inside loop i'm checking if there is any attachment with that record then include it inside map otherwise put a blank reference.Now if you want to retrieve keys whose attachment list is blank you can use following code:

//Assuming Category__c is a lookup
for(Id categoryId : catAttMap.keyset()){
    if(catAttMap.get(categoryId).size()==0){
         System.debug('this category has zero attachment'+categoryId );
    }
}