Map - Keyset and Values
Not Started

Notice that there are two columns in the table.

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



If someone asked you to share all the Currency Codes we have mappings for, you'd show them the first column. If they asked for all of the exchange rates we have, you'd show them the second column.

We can do that with Apex too. It'll come in really handy in the next lesson when we loop through maps. To retrieve all our map's keys we'd use the keySet() instance method. This method will return all of the keys in the map as a set that matches the datatype of our keys.

Map<String, Decimal> currencyCodeToExchangeRate = new Map<String, Decimal> { 'USD' => 1, 'CAD' => 1.39, 'MXN' => 18.49, 'EUR' => 0.94, 'GBP' => 0.83 } Set<String> allCurrencyCodes = currencyCodeToExchangeRate.keySet();

Be sure that the set you declared matches the datatype of your map's keys. Otherwise you'll have a compilation error:

Map<String, Decimal> currencyCodeToExchangeRate = new Map<String, Decimal> { 'USD' => 1, 'CAD' => 1.39 }; Set<Integer> allCurrencyCodes = currencyCodeToExchangeRate.keySet(); // Compilation Error: Illegal assignment from Set<String> to Set<Integer>

This datatype is Set because the keys are unique. This is a fully functioning set - so you can apply any of the set instance methods on the allCurrencyCodes variable.

We can retrieve the values of a map using the values() instance method. The method will return the map's values as a list:

Map<String, Decimal> currencyCodeToExchangeRate = new Map<String, Decimal> { 'USD' => 1, 'CAD' => 1.39, 'MXN' => 18.49 } List<Decimal> allExchangeRates = currencyCodeToExchangeRate.values();

If our map is empty, our list would be empty:

Map<String, Decimal> currencyCodeToExchangeRate = new Map<String, Decimal>(); List<Decimal> allExchangeRates = currencyCodeToExchangeRate.values();

If our map was never initialized or was null, we'd have a bad time:

Map<String, Decimal> currencyCodeToExchangeRate; List<Decimal> allExchangeRates = currencyCodeToExchangeRate.values(); // YIKES!

Because currencyCodeToExchangeRate is uninitialized it's Null. We can not use the dot operator on a null variable. We'd be faced with this runtime error when our code runs: System.NullPointerException: Attempt to de-reference a null object.

That's the end of the course! You now have a solid foundation with Apex Collections and are ready for the next course. Congrats!

Challenge

In the processShoppingCart method - extract the keys and values from productToPriceMap and set the instance variables.

Code similar to this may call your code:

Map<String, Decimal> productToPriceMap = new Map<String, Decimal>(); productToPriceMap.put('Flour', 3.99); productToPriceMap.put('Oil', 8.99); productToPriceMap.put('Instant Yeast', 6.99); ShoppingCartController controller = new ShoppingCartController(); controller.processShoppingCart(productToPriceMap);