1

I have a requirement.for that I create a trigger. on that trigger I am using the Opportunity -Sobject and List of OpportunityContactRoles comes under the opportunity. Now I form the map as followingly

if (!(MapName.containsKey(mapkey))) {
    triggerNewMap.put( KEY, new List<OpportunityContactRole>());
}
triggerNewMap.get(mapkey).add(OpportunityContactRolevalue);

in this here if I give the input on followingly,

  1. mapkey1, OpportunityContactRoleList1
  2. mapkey2, OpportunityContactRoleList2
  3. mapkey1, OpportunityContactRoleList1

Then how to prevent the last one case? for any answers thanks in advance.

  • If you're setting OpportunityId, ContactId, and Role, you might not need the Map at all. Set considers all fields in the SObject when doing duplicate checks. – sfdcfox Jan 13 '17 at 13:29
2

You have to modify the type of values of your map. Currently you have:

Map<String, List<OpportunityContactRole>> triggerNewMap = new Map<String, List<OpportunityContactRole>>();

You have to change it to a Set :

Map<String, Set<OpportunityContactRole>> triggerNewMap = new Map<String, Set<OpportunityContactRole>>();

The Set class contains a contains() method. You can check if the set already contains the value before adding it.

  • Isn't SObject by themself are not hashed properly? I know you can use Set<Id>, but not Set<Account>. I think same apply to Opportunity ContactRole – ytiq Jan 13 '17 at 9:50
  • @ytiq I'm sorry for the prior comment notification. I had linked the wrong question. I have a working demo of using an SObject as a key in a map. You can also use them in a Set. It's all about how you design your setup; they must contain the same fields and the same values to be a match. I've used this for all kinds of data deduplication, because I don't have to create a custom class just to handle the situation of finding duplicates. – sfdcfox Jan 13 '17 at 13:27

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.