1

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.

  • Is there a relationship between the two objects? I should not have to say this at this point How to Ask – Eric Apr 26 '17 at 22:01
1

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);

  }
}
|improve this answer|||||
  • clarified the last loop - it is a separate function or lives inside the first loop. – Caspar Harmer Apr 26 '17 at 22:21
  • No probs - it's always a handy technique – Caspar Harmer Apr 27 '17 at 22:30

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.