How can I get the key as well as the value at the top for the loop?

I have a map object that is stored <Id, String>where Id is the contact identifier, and the line is the generated email.

I successfully walked through the map and was able to pull out the values ​​(part of String) when I iterate over the map.

What I would like to have is also to capture the key when I capture the value. This is very easy to do in most languages, but I can’t figure out how to do this on top.

This is what I have right now:

Map<Id,String> mailContainer = new Map<Id,String>{};

for(String message : mailContainer.values())
{

    // This will return my message as desired
    System.debug(message);

}

What I would like is something like this:

for(String key=>message : mailContainer.values())
{

    // This will return the contact Id
    System.debug(key);

    // This will return the message
    System.debug(message);

}

Thanks in advance!

+5
source share
3 answers

Key iterations instead of values:

for (Id id : mailContainer.keySet())
{
    System.debug(id);
    System.debug(mailContainer.get(id));
}
+11
source

, . Apex , (, ).

0

What it costs for is another way to accomplish this (a bit more verbose) ...

    Map<id, string> myMap = Map<id, string> ();

    set<id> keys = myMap.keySet();
    for (id k:keys) {
        system.debug(k +' : '+ myMap.get(k));
    }
0
source

All Articles