We're going to go through these next few instance methods quickly. I have full faith in you!
When we add key/value pairs to a map, we're increasing the size of a map. We can determine the size of a map using the size()
instance method:
Map<String, Decimal> currencyCodeToExchangeRate = new Map<String, Decimal> { 'USD' => 1, 'CAD' => 1.39, 'MXN' => 18.49, 'EUR' => 0.94, 'GBP' => 0.83 }; Integer mapSize = currencyCodeToExchangeRate.size(); // returns 5
We can remove a key and value pair from a map using the remove(key)
instance method. This method will remove the pairing and return the value that was removed:
Map<String, Decimal> currencyCodeToExchangeRate = new Map<String, Decimal> { 'USD' => 1, 'CAD' => 1.39, 'MXN' => 18.49, 'EUR' => 0.94, 'GBP' => 0.83 }; Decimal valueRemoved = currencyCodeToExchangeRate.remove('EUR'); // Returns 0.94 Integer mapSize = currencyCodeToExchangeRate.size(); // returns 4 Decimal eurExchangeRate = currencyCodeToExchangeRate.get('EUR'); // returns NULL valueRemoved = currencyCodeToExchangeRate.remove('EUR'); // Returns NULL because it's not in the Map anymore
Let's keep this lightning round going. To check if a map is empty, we can use the isEmpty()
instance method, which returns a boolean value:
Map<String, Decimal> currencyCodeToExchangeRate = new Map<String, Decimal>(); Boolean isMapEmpty = currencyCodeToExchangeRate.isEmpty(); // returns TRUE currencyCodeToExchangeRate.put('USD', 1); isMapEmpty = currencyCodeToExchangeRate.isEmpty(); // returns FALSE Map<Integer, String> idToName; isMapEmpty = idToName.isEmpty(); // Runtime Error! System.NullPointerException: Attempt to de-reference a null object