
How to initialize a list of strings in Apex?

I have a Map<String, Object>
named idCollection
.
Retrieval of a single string value is achieved through:
Object accountIdObject = idCollection.get('accountId');
I have confirmed that accountIdObject
is indeed a string. My goal is to incorporate it into a List<String>
named accountId
.
In Java, this task is straightforward, allowing the direct assignment of a single string to a new list:
List<String> accountId = Arrays.asList((String) accountIdObject);
What’s the optimal approach for similar initialization in Apex?
I attempted the following, which resulted in the error: Illegal assignment from Object to List.
List<String> accountId = new List<String>{(String) accountIdObject};
However, I’ve verified that accountIdObject
is a string, as indicated by accountIdObject instanceof String
returning true.
Answer:
A detailed version of the desired code would be:
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;
}
For a more concise form of code, consider:
List<String> accountId = accountIdObject instanceof String
? new List<String>{ (String) accountIdObject }
: (List<String>) accountIdObject;
For project based hands-on salesforce training contact us.