2

In Java we can iterate over Map easily and we can see what values are present for each key.

Map<String, String> map = ...
for (Map.Entry<String, String> entry : map.entrySet()) {
    System.out.println(entry.getKey() + "/" + entry.getValue());
}

How can I do the same in Apex?

Sample code:

Map<String, String> cityCountryMap = new Map<String, String>();
cityCountryMap.put('India','Delhi');
cityCountryMap.put('Sri Lanka','Colombo');
cityCountryMap.put('Nepal','Bhutan');
cityCountryMap.put('Pakistan','Islamabad');

for(String country : cityCountryMap.keySet()){
    System.debug('Country : '+ country);
}

for(String city : cityCountryMap.values()){
    System.debug('City : '+city);
}
  • I'd argue that Apex is quite mature, just...quirky. – Derek F Apr 13 '17 at 18:39
9

Simply

   for(String country : cityCountryMap.keySet()){
    System.debug('Country : '+ country);
    System.debug(cityCountryMap.get(country);
}
|improve this answer|||||
7

Use Map.get() to retrieve the value of the key.

for(String country : cityCountryMap.keySet()){
    System.debug('Country : '+ country);
    System.debug('City : '+cityCountryMap.get(country));
}
|improve this answer|||||
  • 3
    There is an echo on SFSE lately lol. That's a good sign – Eric Apr 13 '17 at 18:17
  • 2
    The timestamps for both of these answers are 18:13:17... impressive! – Robert Watson Apr 13 '17 at 22:26
  • 2
    @RobertWatson - How do you see the exact timestamps? I knew we were within seconds of each other. if Santanu had not been so verbose he would have beat me lol – Eric Apr 13 '17 at 22:37
  • @Eric if you hover over the "answered X hours ago", a tooltip will appear with the exact time. – Robert Watson Apr 14 '17 at 17:08

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.