I'm having an issue with the Map Collection. I'm trying to merge some duplicates. I have value that identifies the dupes Number__c and is appearing on multiple accounts that need to be merged.

I'm trying to create a map that has the Number__c as the key for the list of Account records that have that id. However, I end up creating a the same list for ever Key (Number__c) in the Map.

Output is currently like this.

  • Key = 1, List ( Id001, Id002, Id003)
  • Key = 2, List ( Id001, Id002, Id003)
  • Key = 3, List ( Id001, Id002, Id003)

Here is the code so far. I completed the SOQL query earlier to get All accounts for the loop.

for(integer i=0; i < allAccts.size(); i++){    
             if (allAccts.get(i).Rating__c == 'Do Not Use' ) {
                 masterRec = allAccts.get(i);

            List<Id> dupes = new List<Id>(); 
            for(Account b : allAccts){  
                 if (masterRec.Number__c == b.Number__c && masterRec.Id != b.Id) {


                 mapRaccts.put(masterRec.Number__c, dupes );
  • What is masterRec? Does this code even compile?
    – Nick Cook
    Aug 21, 2019 at 23:33
  • Yes, the code compiles. It was declared further up. See answer below it works. I had initialized masterRec prior to the loop.
    – thinker
    Aug 22, 2019 at 12:21

1 Answer 1

  • The problem is that you assigning every account as master account masterRec = allAccts.get(i) and adding all the accounts to the list for each key dupes.add(b.Id) and so for every key, you are getting all accounts.

Also note below points:

  • This is a very low performant code because you are iteration over all accounts for each account because of inner loop. So, just for 100 accounts, you will be iteration 10,000 times.
  • You should be iteration over generic for loop for (variable : list_or_set) instead of for (init_stmt; exit_condition; increment_stmt) so that you dont have to depend on size(). Check here.

Below is the code you can implement:

    List<Account> allAccts  = [SELECT Id, Name, Number__c FROM Account LIMIT 50000];
    Map<String, List<Account>> dupesMap = new Map<String, List<Account>>();

    for(Account acc : allAccts) {
        if(!dupesMap.containsKey(acc.Number__c)) {
            dupesMap.put(acc.Number__c, new List<Account>());

    // further processing of dupesMap
  • 1
    Thank you sir! The information you gave me here is something I had been trying to figure out and has many more implications for my other projects. Really appreciate your help. #GreenCheck
    – thinker
    Aug 22, 2019 at 12:20

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.