function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Phuc Nguyen 18Phuc Nguyen 18 

Convert for loops with Lists into Maps

Hello All,
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 teh 2 maps:
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.get(Pear_c)){
                    rec1.Test__c = result1.Id;
                }
            }
        }

 
Best Answer chosen by Phuc Nguyen 18
Suraj Tripathi 47Suraj Tripathi 47
Hi Phuc,
Please find the your solution:
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 );
if( !records1.containsKey() !=null && !records2.containsKey() !=null ){
    for( object1__c rec1 : records1.values() ) {
       if (rec1.Apple__c = records2.get(Pear_c) ) {
         rec1.Test__c = result1.Id;
       }
     }
  }

Hope this helps, If you find your solution please mark it as the best answer.
Thanks