[SalesForce] Removing Duplicate from map

I have created a map of type

Map<Id, Set<Id>> missingProduct= new Map<Id, Set<Id>>();
Set<Id> prd = new Set<Id>(); 

However on running the loop and storing the values duplicate map values are been stored without removing the value of the previous map.

for(Product_Objective__c  prdObj :allObjectives ){ 
      prdobject = new Product_Objective__c  ();

      prd.add(prdobject.Product__c);


      missingProduct.put(prdobject.Account__c,prd);

      system.debug('missingProduct'+missingProduct);
}  

Map is having the values of the previous set also stored with all value. I am unable to make it null for new key.

 Set<Id> prd = new Set<Id>(); 

Best Answer

I am guessing that Product_Objective__c is a child of Account and you want a map of AccountIds to a set of Product_Objective__c Ids.

You need to check if the map contains the account id or not, if yes fetch the existing set from the map and then add the new item or create a new set and put in the map.

Problems with your existing code.

for(Product_Objective__c  prdObj :allObjectives ){ 
      prdobject = new Product_Objective__c  (); //new instance

      prd.add(prdobject.Product__c); //so, Product__c will be null anyway.


      missingProduct.put(prdobject.Account__c,prd); //putting the one id Set against the account id.
//you are not nullifying the set here to reuse it next time.
      system.debug('missingProduct'+missingProduct);
}

Rather, make it cleaner.

for(Product_Objective__c  prdObj :allObjectives ){ 

    if(missingProduct.containsKey(prdObj.Account__c))
    {
        missingProduct.get(prdObj.Account__c).add(prdObj.Id);
    }
    else
    {
        missingProduct.put(prdObj.Account__c, new Set<Id>{prdObj.Id});
    }
}
System.debug('missingProduct'+missingProduct);

This should give you a map of Account Ids to a set of Product_Objective__c Ids.

Related Topic