function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Pratiksha ShevadePratiksha Shevade 

Looping over a map throes Null Pointer Exception

Why  am I getting a Null Pointer Exception during iterating a map in a FOR loop, even if there are corresponding values in the map?
system.debug('**stdmap**' + stdIdToxyzMap.get(std.id)); //Prints the values correctly. No Null pointer exception          
for(xyz__c x : stdIdToxyzMap.get(std.Id)){  //Throws Null Pointer Exception at this line
	system.debug('x:'+x.id);
}
Best Answer chosen by Pratiksha Shevade
Suraj Tripathi 47Suraj Tripathi 47
Hi Pratiksha,

You can take reference from this below code.
if(stdIdToxyzMap.containskey(std.Id){
system.debug('**stdmap**' + stdIdToxyzMap.get(std.id));
for(xyz__c x : stdIdToxyzMap.get(std.Id)){ 
	system.debug('x:'+x.id);
}
}

In case you find any other issue please mention. 
If you find your Solution then mark this as the best answer. 

Thanks and Regards
Suraj Tripathi.

All Answers

Suraj Tripathi 47Suraj Tripathi 47
Hi Pratiksha,

You can take reference from this below code.
if(stdIdToxyzMap.containskey(std.Id){
system.debug('**stdmap**' + stdIdToxyzMap.get(std.id));
for(xyz__c x : stdIdToxyzMap.get(std.Id)){ 
	system.debug('x:'+x.id);
}
}

In case you find any other issue please mention. 
If you find your Solution then mark this as the best answer. 

Thanks and Regards
Suraj Tripathi.
This was selected as the best answer
Pratiksha ShevadePratiksha Shevade
Thanks Suraj!
I was running this in another for loop so for one of the keys, the values were coming as NULL and hence it was throwing the exception. Adding the null check before the loop solved the issue.
Suraj Tripathi 47Suraj Tripathi 47
Yes pratiksha Shevade.
If you find your Solution then mark this as the best answer.