Map Collection

  • Map is a Key-Value pair collection, which allows us to store a collection of elements.
  • Map collection allows us to store both Homogeneous and Heterogeneous elements inside it.
  • i.e. Upon inserting the element, we have to supply both “Key and Value” pair. Where Key should be always Unique, and Value may be Unique or may be Duplicate.
  • Map collection supports the Dynamic Memory Allocation, which makes the collection size can Grow / Shrink at runtime.
  • Map collection allows us to store the elements of type “Primitive Type, SObject Type, Collection Type, Apex Types and User Defined Types”.

Syntax:   Map<KeyDataType, ValueDataType> <objectName> = new Map<KeyDataType, ValueDataType>();

Ex:  Map<String, String> countryCodes = new Map<String, String>();

Map<Id, Account> accountsMap = new Map<ID, Account>();

Map<ID, Integer> childRecordsMap = new Map<ID, Integer>();

Map Methods

1. Put(<Key>,<Value>): Add a New Element into the Map Collection.






2. PutAll(<SourceMapCollectionName>):

    We can copy all the elements from Source Map Collection to Target Map Collection.

Ex:   fruitsMap.PutAll(<MapCollectionName>);

3. Integer Size():

4. Boolean IsEmpty():


      if( fruitsMap.isEmpty())

               system.debug(‘Collection is Empty.’);


               system.debug(‘Collection is Not Empty.’);

5. Get(<KeyName>):

  By using this method, we can get the Value of the element based on the specified Key.

Ex:  system.debug(‘Value of element Red is…: ‘+ fruitsMap.Get(‘Red’)); –> Apple

6. Boolean ContainsKey(<KeyName>):

       Returns TRUE, when the specified Key found in the collection. Else it returns FALSE.



        system.debug(‘Key Found in the collection.’);


        system.debug(‘Key Not Found. Invalid Key Name.’);

7. Remove(<KeyName>):

     It will remove the Element from the collection, based on the specified Key.




          system.debug(‘Element Found.’); 


          system.debug(‘Element Removed Successfully.’);



         system.debug(‘Element Not Found. Invalid Key Name.’);

8. Clone(): Used to Create a Duplicate Copy of the Map Collection.

Ex:  Map<String, String> backupCopy = fruitsMap.Clone();

9. Set<DataType> KeySet(): It returns all the Key Names in the form of “Set” Collection class.

Ex:  Set<String> keysCollection = fruitsMap.KeySet();

10. List<DataType> Values(): It returns all the Element values in the form of “List” Collection.

Ex:  List<String> valuesCollection = fruitsMap.Values();

11. Boolean Equals(<MapCollectionName>):

       It returns TRUE, when both the Map collections are Identical. Else it returns FALSe.



            system.debug(‘Both Collections are Identical’);


           system.debug(‘Both Collections are Different.’);