I am trying to map the account name with the related phone numbers

set<String> phoneNumbers = new set<String>();
Map<String, set<String>> clientNamePhone = new Map<String, set<String>>();
List<OpportunityContactRole> ocrList = [SELECT Id, Contact.Account.Id,Contact.Name,contact.Account.PersonMobilePhone,contact.Account.PersonHomePhone,contact.Account.WorkPhone__pc
                                           FROM OpportunityContactRole];

    for(OpportunityContactRole ocr: ocrList){

ofcourse I am getting the output as:

{001S000003M1bAaIAJ={+1123456789, +19999999999, +1787878990}, 001S000003M1bAaIBJ=(already output)}

instead I want something like this

{001S000003M1bAaIAJ={+1123456789, +19999999999 }, 001S000003M1bAaIBJ={+1787878990}}

how can I get that map?

Thanks in advance!

1 Answer 1


Right now, you're mashing all numbers for all accounts into a single set. To keep numbers separated, you need separate sets.

You should be able to fix this with the standard map population pattern:

  • Check to see if your map already has the key value you're currently working with
  • If not, put the key into the map (along with an empty set)
  • In all cases, get the set from the map, and add numbers to it
// There is no need to check if ocrList is empty before looping over it.
// If it is empty, the loop will just simply be skipped
for(OpportunityContactRole ocr: ocrList){
    // There's no real point in repeating "ocr.Contact.Account" over and over
    //   again.
    // Save yourself some work by taking advantage of the fact that
    //   parent relationship fields are fully-fledged SObject instances
    Account acct = ocr.Contact.Account;

        // This is the important part!
        // You need a completely separate set for each account id
        clientNamePhone.put(acct.Id, new Set<String>());

    // clientNamePhone.get() will return a set
    // set has the ".addAll()" method
    clientNamePhone.get(acct.Id).addAll(new Set<String>{
  • Ahhh got it, I misunderstood the concept, thank you sooo much for the explanation @DerekF this definitely helps me in building other part of my requirement! Thanks again!! Commented Apr 13, 2022 at 2:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .