2

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>(); 
  • 4
    what's your requirement ? what are you trying to achieve ? in the for loop you are creating a new instance of Product Objective and using its fields (which will all be null to start with) – Vamsi Krishna Mar 28 '17 at 11:33
  • Inside the loop check for the key, does map contains the key or not using Map.containsKey(key). – itzmukeshy7 Mar 28 '17 at 11:41
7

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.

  • 1
    I tend to prefer adding the empty set for missing keys and then unconditionally adding elements, but it basically amounts to the same thing. – Adrian Larson Mar 28 '17 at 13:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.