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

Map collection in apex

What is a map?

A map is a collection of key value pairs. The keys are always unique having a value associated.

Key and values can be of any of the following data types in apex:

  • Primitive types, like string, integer etc..
  • Collections, like list, set etc..
  • SObjects
  • User-Defined types

When to use a map

A map can be utilized in the following scenarios in salesforce:

  • Relating records based on a unique identifier.

    To relate Contact records to their respective Account records, use a Map with AccountId as the key and a list of Contact records as the value.

  • Aggregation of data based on a unique key.

    To calculate total Opportunity amounts per Account, use a Map with AccountId as the key and the total Opportunity Amount as the value.

  • Building quick look ups

    To create a quick lookup for country capitals, use a Map with the country code as the key and the capital as the value.

How to declare a map?

You can declare a map using the Map<key, value> syntax. Following is an example of a map with string key and value.

Loading...

In the above example:

  • The keyword Map is used to declare a map which can hold key value pairs.
  • The Id is the key and the Account is the value.
  • The variable name mapIdAccount can be used to operate (put/remove etc) on the Map.