[SalesForce] How to compare one Map keyset with another Map’s field-value

I am trying to compare a map that contains Contact ids to the Map that holds ContactId as one of the fields that I have queried in each key-value pairs.

Map<Id, Contact> relatedContIdsMap = new Map<Id, Contact>(selectedContacts);
Map<Id, OpportunityContactRole> relatedOppConRoleMap = 
                    new Map<Id, OpportunityContactRole>([Select Id, ContactId 
                                                        From OpportunityContactRole
                                                        Where OpportunityId 
                                                        IN :relatedOppMap.keySet() ]);

How can I have a condition to compare the ContactIds of the map: relatedContIdsMap to the ContactIds that are retrieved in the map: relatedOppConRoleMap.

I have come across this: containsKey(key) from the developer docs, which seems to compare the actual key of a map, but not a particular field inside a map.

Best Answer

You can't, at least not without iterating over the values of your relatedOppConRoleMap (which, at first glance, kinda defeats the purpose of storing your OpportunityContactRoles in a map in the first place).

To get around this issue, you can simply iterate over your query results and build your map by yourself (instead of using the map constructor).

Map<Id, Contact> relatedContIdsMap = new Map<Id, Contact>(selectedContacts);
Map<Id, OpportunityContactRole> relatedOppConRoleMap = new Map<Id, OpportunityContactRole>();

for(OpportunityContactRole ocr :[Select Id, ContactId From OpportunityContactRole Where OpportunityId IN :relatedOppMap.keySet()]){
    relatedOppConRoleMap.put(ocr.ContactId, ocr);
}

// You can now access the OCR records based on the contactId
for(Contact cont :relatedContIdsMap.values()){
    OpportunityContactRole myOCR = relatedOppConRoleMap.get(cont.Id);
}

// ...or do other operations, like getting rid of all of the OCRs for 
//   Contacts that you didn't previously select
relatedOppConRoleMap.keySet().retainAll(relatedContIdsMap.keySet());
Related Topic