You need to add a null check to your guard condition.

 if (accountRecordTypes == null || accountRecordTypes.isEmpty()) {

The corresponding member that automagically exists behind the property won't be initialised until you call accountRecordTypes = new Map<String, String>();. So the original call to .isEmpty() would have been on null.

As Jesse Altman commented, the null check alone is probably preferable here. If there are no RecordType records that match the SOQL query you don't want to be running the query code again every time the property is called.

Answer from Daniel Ballinger on Stack Exchange
🌐
Forcetalks
forcetalks.com › home › salesforce® discussions › how do you check if a map is empty or not?
Salesforce | How do you check if a map is empty or not? - Forcetalks
September 7, 2020 - Activity › Forums › Salesforce® Discussions › How do you check if a map is empty or not? Salesforce® Discussions · Posted by Marziya on September 7, 2020 at 1:34 PM · How do you check if a map is empty or not? Kirandeep replied 5 years, 5 months ago 2 Members ·
Discussions

java - What is the optimal way to check if a map contains any empty values or keys? - Stack Overflow
I have a map that stores a set of questions and answers. There cannot be questions with empty answers or answers with empty questions. Below is how I have initialized my map. Optional More on stackoverflow.com
🌐 stackoverflow.com
How to check check Map is Empty or null in Visualforce page dynamically in <apex:repeat> - Salesforce Stack Exchange
I already referred link : How to handle maps with no key match and unable to implement logic something simillar, because every time I am getting fields in a Map is dynamic. I have a below logic More on salesforce.stackexchange.com
🌐 salesforce.stackexchange.com
January 13, 2018
apex - How do I check if a list-value from my Map is empty? - Salesforce Stack Exchange
When you execute it, You get null for acclist1 and empty list for acclist2. ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... Community Asks Sprint Announcement – January 2026: Custom site-specific badges! 1 Trigger not working, not able to understand the concept of list map... More on salesforce.stackexchange.com
🌐 salesforce.stackexchange.com
December 3, 2019
Feed Item Detail | Salesforce Trailblazer Community
Skip to main content · Bring your team and maximize your impact at Dreamforce. Register three or more to unlock $999 passes More on developer.salesforce.com
🌐 developer.salesforce.com
July 5, 2015
🌐
YouTube
youtube.com › binary programming
isEmpty() method implementation of Map class in Apex Salesforce #salesforce #salesforcedeveloper - YouTube
#salesforce #salesforceapex #salesforceturotials Use of isEmpty() method of Map Class in SalesforceTrailhead Challenges, Admin Beginner, Admin Intermediate, ...
Published: June 21, 2024
Views: 34
🌐
YouTube
youtube.com › watch
Apex Map Operations: Check for Emptiness & Clearing #coding #sfdcstop #salesforcedeveloper #shorts - YouTube
Aloha Trailblazers, Let's learn how can we check if a map is empty in apex using isEmpty(). We'll also learn how we can remove all values from a map in apex ...
Published: April 24, 2025
🌐
Salesforce
trailhead.salesforce.com › trailblazer-community › feed › 0D54V00007T4XxFSAV
Problem with Null value in Map - Trailhead - Salesforce
Skip to main content · Bring your team and maximize your impact at Dreamforce. Register three or more to unlock $999 passes
🌐
Grabthiscode
grabthiscode.com › whatever › check-map-is-empty-in-apex
Check map is empty in apex - code example - GrabThisCode.com
June 19, 2021 - if (accountRecordTypes == null || accountRecordTypes.isEmpty()) { 0 · empty · check · map · apex truncate string if it is longer · typo3 check if query result is empty · loop through map apex · apex list remove duplicates · salesforce apex null check ·
🌐
Pablo Gonzalez
pablogonzalez.io › should-apex-methods-ever-return-null
Clean Apex: Should you return null, empty or throw an exception?
September 4, 2024 - In this case, the caller still ... == false){ //do something with the user } Here, we use the getPopulatedFieldsAsMap() method from the sObject class to get a map of all the fields that have been populated in memory for ...
Find elsewhere
🌐
Medium
suresh-kandru.medium.com › simplifying-null-checks-in-salesforce-apex-with-the-safe-navigation-operator-211b06ba18ed
Simplifying Null Checks in Salesforce Apex with the Safe Navigation Operator | by Suresh Kandru | Medium
October 29, 2023 - Above code will throw a null pointer exception if the map doesn’t contain the given key. Developers need to do null check like below to avoid null pointer exception
🌐
CRS Info Solutions
crsinfosolutions.com › home › collections in apex programming of salesforce
Collections in Apex Programming of Salesforce
Salesforce Training - The size() method is used to determine the number of key-value pairs in a map. It returns an integer representing the total count of entries in the map. This method is helpful when you need to know how many items are stored in the map, such as when checking if the map is empty or when iterating ... I have enrolled for Salesforce Admin and development online course at CRS info solutions. It’s really the best training i have ever taken and syllabus is highly professional
Rating: 5 ​
🌐
Stack Exchange
salesforce.stackexchange.com › questions › 204516 › how-to-check-check-map-is-empty-or-null-in-visualforce-page-dynamically-in-apex
How to check check Map is Empty or null in Visualforce page dynamically in <apex:repeat> - Salesforce Stack Exchange
January 13, 2018 - Try checking rendered="{!NOT(mapIsEmpty)}" Share · Improve this answer · Follow · answered Jan 15, 2018 at 5:03 · Anshul · 1 1 · Not working at all · Kanika – Kanika · 2018-01-15 07:55:53 +00:00 Commented Jan 15, 2018 at 7:55 · Add a comment | Start asking to get answers · Find the answer to your question by asking. Ask question · Explore related questions · apex ·
🌐
Salesforce Developers
developer.salesforce.com › forums
Feed Item Detail | Salesforce Trailblazer Community
July 5, 2015 - Skip to main content · Bring your team and maximize your impact at Dreamforce. Register three or more to unlock $999 passes
🌐
SFDC Stop
sfdcstop.com › 2024 › 08 › collections-in-apex-salesforce-apex.html
Collections in Apex - Salesforce Apex Tutorial Part 8 to 13 | Code Snippet - SFDC Stop
' + studentsMap.isEmpty()); // * Remove all elements from the map System.debug('Clearing elements inside studentsMap...'); studentsMap.clear(); // * Check if map is empty System.debug('Is student map empty?
Top answer
1 of 2
1

I see that the batch query does not have the filtering condition 'Contact__c != null'. So, it's possible that one of the benefit records is missing value in the 'Contact__c' field and you wouldn't find it in the map. You can solve this in two ways:

  1. Add 'Contact__c != null' to the selector query if you don't care about those records.

(Or)

  1. Check for 'null' value in the for loop as below:

    if(!ConMap.isEmpty())
    {
        for(Benefit__c ben : ConMap.values())
        {
            if(String.isBlank(ben.Contact__c)){
                /* continue;
                   or
                   throw exception()
                */
            }
    
            Task taskObj = new Task();
            taskObj.OwnerId = ConMap.get(ben.contact__c).contact__r.OwnerId;
    
2 of 2
0

I re wrote the code to resolve this nd optimize the code as below.

public with sharing class MyBatch implements Database.Batchable<AggregateResult>{
public Iterable<AggregateResult> start(Database.BatchableContext context)
{
    return [
        SELECT Contact__c, Contact__r.OwnerId owner FROM Benefit__c
        WHERE Contact__c != null AND ...
        GROUP BY Contact__c, Contact__r.OwnerId
    ];
}
public void execute(Database.BatchableContext context, List<AggregateResult> scope)
{
    Set<Id> contactIds = new Set<Id>();
    List<Task> tasks = new List<Task>();
    for (AggregateResult aggregate : scope)
    {
        Id ownerId = (Id)aggregate.get('owner');
        Id contactId = (Id)aggregate.get('Contact__c');

        contactIds.add(contactId);
        tasks.add(new Task(OwnerId=ownerId, /*other fields*/));
    }
    insert tasks;

    List<Benefit__c> benefits = [
        SELECT Id FROM Benefit__c WHERE Contact__c IN :contactIds
    ];
    for (Benefit__c benefit : benefits)
        benefit.Task_Created__c = true;
    update benefits;
}
public void finish(Database.BatchableContext context) { /*additional logic*/ }}
🌐
Beyondthecloud
blog.beyondthecloud.dev › blog › how-to-check-if-list-is-empty-in-apex
How to check if list is empty in Apex | Beyond The Cloud
February 27, 2025 - 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: