Search code examples
listsalesforcesubqueryapexsoql

Salesforce Apex: List.add( value || 'default value')?


After querying for Account sObjects, I'm adding all the fields into a List. The problem is that some Account sObjects have certain fields and others do not. While adding the fields to my list, I'd like to be able to add field if it exists OR add a default string.

Let's go through the example.

My query:

    List<Account> accountQuery = [SELECT name, (SELECT name, id FROM Contacts) FROM Account];

My map:

    Map<String, List<String>> Result = new Map<String, List<String>>();

Iterating through the queryResult and saving the values:

For(Account i : accountQuery){
    String[] temp = new list<string>();
    temp.add(i.name)
    //Now loop through contacts subquery
    if(!i.contacts.isEmpty()){
        for(contact j : i.Contacts){
            temp.add(j.name || 'No Contact Name Associated'); //Doesn't work
            temp.add(j.id || 'No Contact Id Associated');
        }
    }
    else{
        temp.add('No Contact Name Associated');
        temp.add('No Contact Id Associated');
    }
};

How can I achieve this temp.add(value || 'default value')?

Thank you!


Solution

  • What is the purpose of these manipulation with these strings? What do you need to do? I really can't to imagine any use case for this code and I guess that your task might be completed in more convenient way.

    Anyway the answer to your question is using ternary operator - ?:

    tmp.add(j.name != null ? j.name : 'No Contact Name Associated');