Map - Get
Not Started

Now, we'll use the mapping to retrieve a value based on the key. But first, let's visualize our data with a table:

Currency CodeExchange Rate
USD1
CAD1.39
MXN18.49
EUR0.94
GBP0.83



And then convert this table to a map:

Map<String, Decimal> currencyCodeToExchangeRate = new Map<String, Decimal> { 'USD' => 1, 'CAD' => 1.39, 'MXN' => 18.49, 'EUR' => 0.94, 'GBP' => 0.83 };

Now, if I asked you to give me the exchange rate for EUR, what would you do? You'd probably look under the Currency Code column, find EUR, and look across to see the Exchange Rate. We do that programmatically with our map using the get(key) instance method:

Map<String, Decimal> currencyCodeToExchangeRate = new Map<String, Decimal> { 'USD' => 1, 'CAD' => 1.39, 'MXN' => 18.49, 'EUR' => 0.94, 'GBP' => 0.83 }; Decimal eurExchangeRate = currencyCodeToExchangeRate.get('EUR'); // returns 0.94 Decimal mxnExchangeRate = currencyCodeToExchangeRate.get('MXN'); // returns 18.49 Decimal audExchangeRate = currencyCodeToExchangeRate.get('AUD'); // returns NULL, AUD is not in the map

How cool is that? By building out this mapping, we can use Apex to correlate keys with values and easily retrieve them.

Challenge

Create a variable named butterCost. Given groceryItemToPriceMap, retrieve the price of Butter using the .get(key) method and store the result in butterCost.