How do I use a map in Salesforce?
What is a Map in Salesforce?
Ans - a. Map Collection allows us to store Key-Value pairs.
b. Map is an Unordered Collection.
c. In Map, the Key is Unique and Value is Unique or Duplicate.
d. In Map, every element is identified using a Key.
e. Map Class doesn't allow duplicate elements.
Syntax of Map Class -
Map<Key Datatype, Value Datatype> objectName = new Map<Key Datatype, Value Datatype>();
e.g. -
Map<Integer, Integer> customerCodes = new Map<Integer, Integer>();
Methods in Map Class -
1. Put(Key, Value) - used to add a new element inside the collection.
2. PutAll(map_collection) - used to add a collection of elements to the map collection at a time.
3. size() - it returns the size of the collection.
4. isEmpty() - used to check collection is empty or not.
5. Get(KeyName) - used to get the value of a specified key.
6. ContainsKey(KeyName) - used to Find the element in Collection.
7. Remove(KeyName) - used to remove a specified element from the collection.
8. Clear() - used to remove all elements from the Set.
9. Equals(sourceCollection) - used to compare two collections.
10. Set<Datatype> KeySet() - it returns all the key which is present in the collection.
11. List<Datatype> Values() - it returns all the Values which is present in the collection.
e.g. -
Map<string, integer=" "> carPrice = new Map<string, integer=" ">();
carPrice.put('Swift', 900000);
carPrice.put('Honda City', 1200000);
carPrice.put('Scorpio', 1600000);
carPrice.put('xuv', 2200000);
System.debug('List of Car Price is=' +carPrice); </string>
System.debug('Total Number of Car in Collection is:' +carPrice.size());
integer carModel = carPrice.get('swift');
system.debug('The swift price is = ' + carModel );
string carName = carPrice.get(2200000);
system.debug('2200000 is the price of Car = ' + carName );