4

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?

4
  • You could use removeAll if its a set but list class doesn't have a remove all Nov 8, 2018 at 16:53
  • 4
    Why did you add them in the first place?
    – Adrian Larson
    Nov 8, 2018 at 16:58
  • 1
    You can see a list of all the methods provided by the List class.
    – David Reed
    Nov 8, 2018 at 17:25
  • 1
    No, there are no shortcuts available in Apex. Any technique you use will involve the use of do, while, or for.
    – sfdcfox
    Nov 8, 2018 at 20:46

1 Answer 1

6

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)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .