28

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
mail.setToAddresses(toAddresses);

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

I appreciate your help, Reena.

49

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
}
2

Hi you can iterate over that like as follows-

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

The marked correct answer is incorrect.

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

Ex:

for (String key : emailDiseaseMap.keySet()) {
    List<String> toAddresses = emailDiseaseMap.get(key);
}
New contributor
D M is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
1
  • 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 at 19:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.