Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Salesforce by (11.9k points)

I have a method that returns a Map<Id, List<Id>>

Here is the method:

private Map<Id, List<Id>> getDbrToAccountMap(Set<Id> dbrIds) {

    Map<Id, List<Id>> dbrAccountMap = new Map<Id, List<Id>>();

    List<Id> accountIds = new List<Id>();

    for(DBR_Group_Member__c member : [select Id, Contact__c, Contact__r.AccountId, DBR__c from DBR_Group_Member__c where DBR__c in: dbrIds]) {

        if(accountIds.isEmpty()) {

            accountIds = new List<Id>();

            dbrAccountMap.put(member.DBR__c, accountIds);

        }

        accountIds.add(member.Contact__r.AccountId);

    }

    return dbrAccountMap;

}

I only want to add to the list of accountIds for a unique DBR_c and unique account of the Contact_c

For example, if I have a DBR number of:

3333 and the contact is John Smith that is on the Acme account (add to the list)

next I have

3333 and the contact is Jane Smith that is on the Acme account (don't add to the list)

next I have

3333 and the contact is Bob Smith that is on the Big Company account (add to the list)

next I have

3333 and the contact is Doug Smith that is on the Big Company account (don't add to the list)

The DBR to account should be distinct.

In my method, I'm returning the accountIds, but they are not distinct based on the DBR. I have to be careful because I don't want to remove a duplicate accountId in the list if the DBR number was different. That would be a valid element in the list.

Any help would be appreciated.

Thanks.

1 Answer

0 votes
by (32.1k points)
edited by

You can solve this problem by using the local set as follows or using a Map < Id, Set < Id >> as your return value.

private Map < Id, List < Id >> getDbrToAccountMap(Set < Id > dbrIds) {

    Map < Id, List < Id >> dbrAccountMap = neenter code herew Map < Id, List < Id >> ();

    Set < String > alreadyExistSet = new Set < String > ();

    List < Id > accountIds = new List < Id > ();

    for (DBR_Group_Member__c member: [select Id, Contact__c, Contact__r.AccountId, DBR__c from DBR_Group_Member__c where DBR__c in : dbrIds]) {

        if (dbrAccountMap.get() == null) {

            dbrAccountMap.put(member.DBR__c, new List < Id > );

        }

        if (!alreadyExistSet.contains('' + member.DBR__c + member.Contact__r.AccountId)) {

            dbrAccountMap.get(member.DBR__c).add(member.Contact__r.AccountId);

            alreadyExistSet.add('' + member.DBR__c + member.Contact__r.AccountId);

        }

    }

    return dbrAccountMap;

}

Enroll in our Salesforce training to become as an Expert in Salesforce! 

Browse Categories

...