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?

  • You could use removeAll if its a set but list class doesn't have a remove all – codeyinthecloud Nov 8 '18 at 16:53
  • 4
    Why did you add them in the first place? – Adrian Larson Nov 8 '18 at 16:58
  • 1
    You can see a list of all the methods provided by the List class. – David Reed Nov 8 '18 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 '18 at 20:46

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' };

// create a set from the list
set<string> aStringSet = new set<string>(aStringList);

// remove blanks and nulls

// convert back to list
aStringList = new list<string>(aStringSet);

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.