18

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.

30

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

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);
   }

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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