Vijay Ganji's answer is pretty good, though I would prefer to use a Set<String>
here instead of a List<String>
.
It won't make a difference in performance (or the list approach might be ever so slightly faster) given the number of values in a multipicklist field are usually very small, but it is slightly less typing.
This takes advantage of the fact that we have a constructor for Set
that takes a list and that we have a constructor for List
that takes a set.
// Split the multipicklist value on semicolons
String strPickListValue = newAccountValue.StopCom__c;
Set<String> picklistValuesSet = new Set<String>(strPickListValue.split(';'));
// Remove the target value
string strValueToRemove = 'abc';
// If the multipicklist doesn't have our target value, the set will simply just
// not be modified.
// Thus, we can remove the if() from Vijay's solution
// This is what saves us some typing (even though we have a little additional
// typing elsewhere)
picklistValuesSet.remove(strValueToRemove);
// Join everything back together again
newAccountValue.StopCom__c = String.join(new List<String>(lstPicklistValues),';');
This is 291 characters vs Vijay's 340, though perhaps the more important thing is that we eliminated 2-3 lines of code (depending on how you count).
As of Summer '23 (API v58.0), the Set
collection type implements the iterable
interface, so we can just feed the set directly to String.join()
instead of converting it back to a List.
newAccountValue.StopCom__c = String.join(lstPicklistValues,';');
This makes the final character count 273
newAccountValue.StopCom__c = '';
not working?if(value == true)
can always be simplified toif(value)
. Likewise,if(value == false)
simplifies toif(!value)
. Just a way to save a bit of typing.