如何获得循环顶点中的键和值



我有一个映射对象,它存储<Id, String>,其中Id是联系人Id,String是生成的电子邮件。

我已经成功地遍历了映射,并且能够在遍历映射时提取值(字符串部分)。

我想做的是在获取值时也获取密钥。这在大多数语言中都很简单,但我似乎找不到如何在apex中做到这一点。

这就是我现在拥有的:

Map<Id,String> mailContainer = new Map<Id,String>{};
for(String message : mailContainer.values())
{
// This will return my message as desired
System.debug(message);
}

我想要的是这样的东西:

for(String key=>message : mailContainer.values())
{
// This will return the contact Id
System.debug(key);
// This will return the message
System.debug(message);
}

提前感谢!

在键而不是值上迭代:

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

您找不到它,因为它不存在。Apex允许对键或值进行迭代,但不允许对关联(键、值)进行迭代。

值得一提的是,这里有另一种实现方法(稍微详细一点)。。。

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

最新更新