1

I would like to update my exsiting code that uses Lists to instead use maps. Here is what I have:

List<object1__c> records1 = new List<object1__c>();
List<object2__c> records2 = new List<object2__c>();

records1 = [SELECT id, name from object1__c ];
records2 = [SELECT id, name from object2__c];
    
    
 Object3__c result1 = (Object3__c ) so;

    if(!records1.isEmpty() && !records2.isEmpty()){
        for (object1__c rec: records1) {
            for(object2__c rec2: record2)
            if (rec.Apple__c == rec2.Pear__c){
                rec.Job_Item__c = result1.Id;
     
            }
        }
    }

I am trying to convert the above to use maps but I am not sure on how to compare the fields between the 2 maps. Would the below code work or Do I need to iterate through both maps? Just trying to reduce the number of for loops:

Map<Id,object1__c> records1 = new Map<Id,object1__c>();
Map<Id,object2__c> records2 = new Map<Id,object2__c>();

Object3__c result1 = (Object3__c ) so;

if(!records1.isEmpty() && !records2.isEmpty()){

    for(object1__c  rec1 : records1.values()){
        if (rec1.Apple__c = records2.getvalues(Pear_c)){
            rec1.Test__c = result1.Id;
        }
    }
}
1
  • 1
    Worthy of note: You don't need to check if a map or a list is empty before using it in a loop (the only thing you need to worry about is if the collection is null). If you attempt to loop over an empty collection, the loop will see that there's nothing to loop over and automatically skip executing the code inside.
    – Derek F
    Oct 28, 2021 at 16:02

1 Answer 1

2

The key of the map of the records that you're comparing against needs to be it's field value that you're using for comparison.

So if you're comparing records1 Apple__c to records2 Pear__c, you need a map of records2 by its Pear__c value. For example

Map<String, Object2__c> object2ByPear = new Map<String, Object2__c>();
for (Object2__c record2 : records2) {
  object2ByPear.put(record2.Pear__c, record2);
}

Then you can loop through a list of records1 and compare using the object2ByPear map.

for (Object1__c record1 : records1) {
  if (object2ByPear.containsKey(record1.Apple__c)) {
    Object2__c matchingRecord2 = object2ByPear.get(record1.Apple__c);
    // to something
  }
}
1
  • Thank you for the reply. To confirm. The original 2 maps cannot be directly compared to each other(it is not in the above code but each map is being populated by a SOQL query ). The variables for the 'for' loop are the same as the maps but this was done for simplicity purposes. Just want to make sure I am understanding the solution you are providing.
    – Phuc
    Nov 1, 2021 at 13:18

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.