The map collection does not have an add()
instance method, instead, it has put(key, value)
. The first parameter accepts the key, the second accepts the value. The datatype of these parameters must match what has been defined in the map declaration.
Here we're mapping a string to a decimal:
Map<String, Decimal> currencyToExchangeRate = Map<String, Decimal>(); currencyToExchangeRate.put('USD', 1); currencyToExchangeRate.put('EUR', 0.94); currencyToExchangeRate.put('CAD', 1.38); currencyToExchangeRate.put('GBP', 0.84;
Here we're mapping a string to an integer:
Map<String, Integer> nameToAge = Map<String, Integer>(); nameToAge.put('Cyrus', 33); nameToAge.put('Frank', 66); nameToAge.put('Layla', 28); nameToAge.put('Ziba', 35); // nameToAge.put('Ziba', '35'); Not allowed! The value must be an Integer
When adding a key/value pair, if the key already exists in the map, the old value will be replaced with the new value.
Map<String, Decimal> currencyToExchangeRate = Map<String, Decimal>(); currencyToExchangeRate.put('USD', 1); currencyToExchangeRate.put('EUR', 0.94); currencyToExchangeRate.put('EUR', 0.96); // The previous value, 0.94 has been removed from the Map
If the key is a string, we'll need to be careful. The key is case-sensitive.
Map<String, Decimal> currencyToExchangeRate = Map<String, Decimal>(); currencyToExchangeRate.put('USD', 1); currencyToExchangeRate.put('EUR', 0.94); currencyToExchangeRate.put('eur', 0.96); // The key and value pairing above is not replaced, eur is considered a different key than EUR