Consider you're tasked with keeping track of usernames and their userIds. If you're provided a userId, you'd need to find the corresponding username. To do this, you could build a table like this to map the data:
UserId | Username |
---|---|
001 | Codey |
002 | Flo |
003 | Ruth |
004 | Astro |
Here, you'd treat userId as your key or your identifier and username as the value identified by that key. The order here doesn't matter too much. Our primary concern is whether we can find the proper value by using a key. This table will work as long as the userIds are unique.
In Apex, the Map
collection represents this type of key and value structure. Think about how silly it would be to try to represent that table with a List
:
List<Integer> userIdList = new List<Integer>{001, 002, 003, 004}; List<String> usernameList = new List<String>{'Codey', 'Flo', 'Ruth', 'Astro'};
Visually we can tell 001
belongs to Codey
, 002
belongs to Flo
and so on - but these elements are not explicitly associated. Instead, we'll use the map collection to create a key and value pairing between userId, an Integer, and username, a string.
Map<Integer, String> userIdToUsername = new Map<Integer, String>();
There are two datatypes within the angle brackets < >
. The first defines the datatype of the key, the second defines the datatype of the value. A common naming convention for map variables is one that clearly communicates what the key and values represent. Reading the variable name above, it's clear that we've intended to map userIds to usernames.
We'll show you how to construct maps in the next lesson.
You'll use Maps a ton as a Salesforce developer. Triggers (which we'll learn about later) have their own Map variables Trigger.oldMap
and Trigger.newMap
which map a sObject's Id to sObject records. You'll also create your own maps frequently to efficiently read and parse data. Think about other things you can map in your life. An address maps to a building, a phone number maps to a person, and an athlete can be mapped to their career points.