Adam Osiecki
written byAdam Osiecki
posted on October 14, 2022
Freelance Salesforce developer, passionate about delivering well-crafted solutions, always willing to walk an extra mile to get the job done. Working with Salesforce platform since 2017.

How to check if list is empty in Apex

In Apex language there are few different methods to check if the list size is empty:

myList.size();
myList.isEmpty();
myList != null;

What is the difference between them, and which one is the best choice? We will try to find the answer in this post.
Let's have a quick introduction to this topic:

Best practice for working with lists in Apex

1) The best practice when working with a list is to initialize them immediately when they are declared:

List<String> myList = new List<String>();

You should avoid declaring null lists:

List<String> myList;
System.debug(myList == null); // true

The reason is that most native list functions (including size() and isEmpty()) do not check if the variable is null internally, so working with null lists may cause NullPointerException:

List<String> mylist;
System.debug(myList.isEmpty());

If you execute the code from the snippet above, the result will be the following:

19:48:20:002 FATAL_ERROR System.NullPointerException: Attempt to de-reference a null object

2) Before checking if the list is empty, consider carefully if the check is really needed. Based on my experience I noticed that there are at least three cases when developers are checking the list even if there is no need to do that:

a) check before DML operation: DML operations on empty lists are not consuming the transaction DML limits:

❌❌❌

List<Account> accountsToInsert = new List<Account>();
if(!accountsToInsert.isEmpty()) { // no need for this check!
    insert accountsToInsert;
}

✅✅✅

List<Account> accountsToInsert = new List<Account>();
insert accountsToInsert;
System.debug(System.Limits.getDmlStatements());  // result will be 0, no DML action was executed on empty list

b) checking if the SOQL query result is empty: there is a common misconception that the SOQL query could return null when the query returns no records. SOQL queries are always returning at least initialised list:

❌❌❌

List<Account> testAccounts = [SELECT Id FROM Account WHERE Name = 'test'];
Integer listSize = 0;
if(testAccounts != null ) { // no need for this check!
    listSize = testAccounts.size();
}

✅✅✅

List<Account> testAccounts = [SELECT Id FROM Account WHERE Name = 'test'];
System.debug(testAccounts != null); // this will always return true
//so we are safe here:
Integer listSize =  testAccounts.size();

c) there is no need to check if the list is empty before the iteration: it's OK to iterate through the empty list, Apex will skip the execution of the code in the loop without any exceptions:

❌❌❌

List<Account> testAccounts = new List<Account>();
if (!testAccounts.isEmpty()) { // no need for this check!
   for(Account acc : testAccounts) {
       System.debug(acc);
   }
}

✅✅✅

List<Account> testAccounts = new List<Account>();
for(Account acc : testAccounts) {
    System.debug(acc);
}

Keep in mind that for loop is not null-safe so if the list is not initialised it will throw an exception:

List<Account> testAccounts;
for(Account acc : testAccounts) {
    System.debug(acc);
}
20:13:52:003 FATAL_ERROR System.NullPointerException: Attempt to de-reference a null object

As a rule of thumb, we can assume that we should always initialise the list variables during the declaration.
This will allows us to skip null checks in the code that we control (eg. code in our class, or any other code that we can modify or check). If we work with a code that we can't control (e.g. consuming methods from the managed package, or maintained by another team where we can't do the code review) it is advised to always do the null-check on variables returned by that code unless the documentation says the opposite.

!= null vs isEmpty() vs size > 0

If we are sure that we want to check if list is empty we have two scenarios:

  • null check is needed (see the section above). In that case we should use:
if(myList != null && myList.isEmpty()) {
    ....
}
  • null check is not needed, we can just skip the null part:
if(myList.isEmpty()) {
    ...
}

myList.size() > 0 method should not be used in this case. Method size() should be restricted only to the cases when we do care about the exact size of the list. The reason is that size() method is more CPU-consuming.

Summary

When you check for the emptiness of a list you should prefer isEmpty() to size(). Before doing the check make sure that this is necessary. If you know of any other cases where checking if the list is not empty, do not hesitate to write it in the comment.


If you have some questions feel free to ask in the comment section below. 🙂

Was it helpful? Check out our other great posts here.


Buy Me A Coffee