6

I have a map object which stores <Id, String> where the Id is a contact Id, and the String is a generated email message.

I have successfully looped through the map and have been able to pull out the values (The String portion) as I iterate through the map.

What I would like to be able to do is also grab the key when I grab the value. This is very simple to do in most languages, but I can't seem to find out how to do it in apex.

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!

tomlogic
  • 11,489
  • 3
  • 33
  • 59
VictorKilo
  • 1,839
  • 3
  • 24
  • 39

3 Answers3

14

Iterate over the keys instead of the values:

for (Id id : mailContainer.keySet())
{
    System.debug(id);
    System.debug(mailContainer.get(id));
}
Adam Butler
  • 2,733
  • 23
  • 27
0

You can't find it because it doesn't exist. Apex allows iterating over either keys or values but not associations (key, value).

tggagne
  • 2,864
  • 1
  • 21
  • 15
  • 1
    You can loop through the keys though, and then use those keys to grab the value. Adam's answer shows this perfectly. You are correct to the extent that I can't iterate over `(key,value)`, but it is still possible to get the same effect with Adam's method. – VictorKilo Oct 02 '12 at 15:09
0

For what it's worth, here's another way to accomplish it (slightly more verbose)...

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

    set<id> keys = myMap.keySet();
    for (id k:keys) {
        system.debug(k +' : '+ myMap.get(k));
    }
sberley
  • 2,238
  • 1
  • 16
  • 12