This course is currently a work in progress. Please join the waitlist to receive regular updates.

Iterating through a map using for loops

In Apex, you cannot directly loop through a map using a for loop. Instead, you can iterate through the map by accessing its keys or values as a collection.

Using Keyset

You can get the keys of a map using the keySet() method. The keysSet() method returns a collection that contains all the keys of the map.

Using Values

Alternatively, use the values() method to retrieve all the values from the map as a collection Then, iterate through the collection using a for loop to process the individual records.

Following is an example of iterating through a map using its keys:

Loading...

In the above example:

  • The variable allContactsMap contains the first 200 contact records from salesforce.
  • The keyset() method is used to return all keys from the map.
  • The for loop iterates through all the keys and individual contact record is accessed using the map get() method.

Try It Yourself

Loading...