How to remove null or empty values from list in apex.I know i could do that with while or for loop.Is there any shortcut way or method available to remove empty and null values in a list?
1 Answer
Do you really need a list, or can you use a set?
// create a list for testing
list<string> aStringList = new list<string> { 'one', 'two', null, 'two', '', 'three' };
system.debug(aStringList);
// create a set from the list
set<string> aStringSet = new set<string>(aStringList);
// remove blanks and nulls
aStringSet.remove('');
aStringSet.remove(null);
// convert back to list
aStringList = new list<string>(aStringSet);
system.debug(aStringList);
The output is:
DrozBook:fsb-maintenance tgagne$ force apex < tooter | grep debug\|
08:25:47.17 (18105078)|USER_DEBUG|[3]|DEBUG|(one, two, null, two, , three)
08:25:47.17 (18243825)|USER_DEBUG|[14]|DEBUG|(one, two, three)
List
class.do
,while
, orfor
.