Iterating over a map (Apex)

I have a map written in Apex.

Map<Id, Set<String>> emailDiseaseMap = new Map <Id, Set<String>> ();

The map contains an ID and then a set of email addresses. I am trying to send an email to all email addresses linked to a certain ID. So I need a for loop, which iterates through the map and then gives me the ID inside one variable, and then the list of email addresses in another variable.

I have written the email part of this task, but just cannot figure out how to iterate over the map to then have a variable with the disease ID and then a list with the patient emails.

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

//get email addresses for specific disease
List<String> toAddresses = new List <String>();

//set addresses for email to be sent

//set up remaining email
mail.setSenderDisplayName('Ms Reena');
mail.setSubject('Planning Application');
mail.setPlainTextBody('This is a test email');

I appreciate your help,


These methods are available for all maps.

So one way to code it is to use a keySet() method of the Map.
Firstly you will get all Id’s (keys) from the map and then will iterate over that set of keys. Based on the key you can then get a corresponding set of emails:

for (Id key : emailDiseaseMap.keySet()) {
    // The "key" variable is also available inside the loop
    List<String> toAddresses = emailDiseaseMap.get(key);
    // ... emailing logic

Source : Link , Question Author : user8737 , Answer Author : Alex Edelstein

Leave a Comment