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.setReplyTo('[email protected]');
mail.setSenderDisplayName('Ms Reena');
mail.setSubject('Planning Application');
mail.setPlainTextBody('This is a test email');

I appreciate your help, Reena.

3 Answers 3


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
    Set<String> toAddresses = emailDiseaseMap.get(key);
    // ... emailing logic

Hi you can iterate over that like as follows-

 for(Id id: mapname.keyset()){
    Set<String> stringset= mapname.get(id);
    for(String a: stringset){

You must iterate over the keyset with a String type, not an Id type.


for (String key : emailDiseaseMap.keySet()) {
    List<String> toAddresses = emailDiseaseMap.get(key);
  • 2
    This is not correct. The keySet of this map is typed as a Set<Id>. Iterating with a loop variable typed as either an Id or a String compiles and runs. There is a bug in the accepted answer, but your code does not fix it - List<String> should be Set<String>.
    – David Reed
    May 4, 2021 at 19:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .