Declaring a map will look really similar to declaring a list or set:
Map<String, String> userIdToUserName;
Here we've declared a variable named userIdToUserName
and assigned the type Map<String, String>
. We'll need to initialize this variable so it's not null:
Map<String, String> userIdToUserName = new Map<String, String>();
On the right-hand side of the equals sign, the new
operator creates a Map<String, String>
. Our variable is no longer null! The ()
is a constructor, so we can keep this empty or optionally pass in another map to initialize:
Map<String, String> userIdToUserName = new Map<String, String>(); Map<String, String> userIdToUserNameDuplicate = new Map<String, String>(userIdToUserName);
As you saw in the last lesson, a map can be initialized directly with key and value pairs using the key => value
structure and the =>
operator.
Map<String, String> userIdToUserName = new Map<String, String>{'Ux001' => 'Codey'};
We're mapping the string key Ux001
to the string value Codey
. Let's use a comma-separated list to initialize the map with more pairs:
Map<String, String> userIdToUserName = new Map<String, String> { 'Ux001' => 'Codey', 'Ux002' => 'Flo', 'Ux003' => 'Ruth', 'Ux004' => 'Astro' }; // Updated the spacing here to improve legibility
The keys of a map must be unique, but the values don't have to be:
Map<String, Decimal> currencyToExchangeRate = new Map<String, Decimal> { 'USD' => 1, 'EUR' => 0.95, 'GBP' => 0.95 }; // EUR and GBP can both exist in the map even though they have the same values