[SalesForce] Connecting fields in two List of objects

I have two list of object.

List<ClassA> and List <ClassB>. ClassA has a field TextA and ClassB has a text field TextB. I want to copy the TextB value to TextA for each object of ClassA. Any idea how to go about this?

How do I loop through both ClassB and ClassA at the same time. I though of using Map but I am not sure how to go about forming key value pair here.

Best Answer

Define a Map<String,String> of linked fields and iterate that instead.

eg:

private static Map<String, String> mapFields = 
new Map<String, String> {'MailingState' => 'State__c', 
                         'MailingStreet' => 'Street__c', 
                         'MailingPostalCode' => 'Zip__c',
                         'MailingCity' => 'City__c'};

Then, iterate over the list of ObjectA (assuming that you want to copy the values to the corresponding ObjectB)

for (Integer i = 0; i< listOfObjectA.size; i++){
  ObjectA obA = listOfObjectA[i];
  ObjectB obB = listOfObjectB[i];
  //call your mapFields function:
  mapFields(obA,obB);
}

In the mapFields function, iterate over your mapFields, copying values:

for (String objAKey : mapFields.keySet()){
  //note, isBlank will only work for Strings - you will need to expand this
  if (!String.isBlank(obA.get(objAKey))){

    ObjAValue = obA.get(objAKey);
    ObjBKey = mapFields.get(objAKey);
    obB.put(ObjBKey,ObjAValue);

  }
}
Related Topic