[SalesForce] What’s the best way to initialize a list of strings in Apex

I have a Map<String, Object> idCollection.

Object accountIdObject = idCollection.get('accountId');

Doing this gets me a single string value. Now I am sure that accountIdObject is a String and have a requirement to add it to a List<String> accountId

Something like this is easily possible in java which would assign the single string to a new list –

List<String> accountId = Arrays.asList((String)accountIdObject);

What would be the best way for such initialization in apex ?

I have tried –
List<String> accountId = new List<String>{(String)accountIdObject};
which is giving an exception Illegal assignment from Object to List. Also I am sure that accountIdObject contains a string value which I have confirmed by doing a accountIdObject instanceof String which returned true.

Best Answer

The long form of what you want looks like:

Object accountIdObject = idCollection.get('accountId');
String[] idValues;
if(accountIdObject instanceOf String) {
  idValues = new List<String> { (String)accountIdObject };
}
if(accountIdObject instanceOf List<String>) {
  idValues = (List<String>)accountIdObject;
}

Given your example code, the condensed version looks like:

List<String> accountId = accountIdObject instanceof String
   ? new List<String>{(String)accountIdObject} 
   : (List<String>)accountIdObject;

When using instanceOf, be aware of the limitations outlined in this post. If it's not a literal List<String>, but some other type that's closely related, you may experience runtime errors.