I have a List of String. This list consist of accountNumbers from Account Object. List<String> accountNumList. I have a child object XYZ__c, which is child of Account Object. XYZ__c object has a custom field called status__c and flag__c

I am looking at an efficient way to build a Map of type Map<String,String>. where Key is the accountNumber and Value is the status__c field of the child object of the corresponding Account. There could be multiple children of a account. I need to get only the child whose flag__c field has 'Active' text in it and use it as the value.

What I think I should do to build this Map:

List<String> accountNumList; // has all the accountNumbers
List<Account> acc =[select id,accountNumber,(select id,status__c,flag__c from child_relation__r where flag__c=='Active') from Account where accountnumber in:accountNumList];

Map<String,String> accountMap = new Map<String,String>();
For(Account a : acc){

Is this an efficient way to build the Map? Any Suggestions!

  • You could still have more than one child with that flag value, no? You still have to consider what to do in case of collision as this scenario is described.
    – Adrian Larson
    May 23 '17 at 21:07
  • There can be only one child with active flag.
    – SfdcBat
    May 23 '17 at 21:09
  • So what is your question?
    – EricSSH
    May 23 '17 at 21:11

You need to index into your list. Before you do so, however, you have to check if the list is empty.

for (Account record : [/*query*/])
    if (!record.Children__r.isEmpty())
        accountMap.put(record.AccountNumber, record.Children__r[0].Status__c);

If you omit the empty check, than any iteration over a record without an active child would throw this error:

System.ListException: List index out of bounds: 0

  • The isEmpty() check is to prevent Null Pointer Exception?
    – SfdcBat
    May 23 '17 at 21:17
  • 1
    @SfdcBat If the child list were null, that check could not possibly prevent a null pointer. It's so you don't get System.ListException: List index out of bounds: 0.
    – Adrian Larson
    May 23 '17 at 21:19

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.