How to Create Map Collection in Salesforce Apex? [With Various Methods]

As a Salesforce developer, I was required to create an Apex method that retrieves a list of opportunities and their related account names and then stores them in a map where the OpportunityId is the key and the Account Name is the value.

Here, I will explain map collections in Salesforce Apex, their methods, and their uses. Then, we will see how to create map collection in Salesforce Apex.

Map Collection in Salesforce Apex

In the map collection, we not only store a single value, but also two values. Where the value is associated with a particular key in the map, the key is always unique, and the value can be duplicated.

The map collection is very useful for storing the record IDs as keys because the key is unique in the map, record IDs are also unique, and record data can be stored as values.

Syntax of declaring Map collection in Apex:

Map<Datatype, Datatype> myMap = new Map<Datatype, Datatype>();

In the Apex code below, I showed you how to declare the set collection in Salesforce Apex.

Here, I declared a map collection with two different data types; you can add the same data type. Then, I added an integer as a key and a string as a value. I entered duplicate keys and values so we could see the result.

Then, I created a map without repeating keys, but there were duplicate values. Now execute this code, and you will see the result.

//Adding Duplicate keys to the Map
Map<Integer,String>AddMapValues= new Map<Integer,String>{101=>'LWC', 102=>'Apex', 103=>'LWC', 101=>'VisualForce'}; 
system.debug(' Values in Map collections are: ' +AddMapValues);

system.debug('---------------------------------------------------------------');

//Without duplicate key
Map<Integer,String>AddMapValue= new Map<Integer,String>{101=>'LWC', 102=>'Apex', 103=>'LWC', 104=>'VisualForce'}; 
system.debug(' Values in Map collections are: ' +AddMapValue);

As you execute the above code, you can see the map removes duplicate keys and displays them only once. Because of removing duplicate keys, the associated value also gets removed.

Then, for the keys without repeating, all key & value pairs are displayed even if there are duplicate values.

How to Create Map Collection in Salesforce Apex

Methods For Map Collection in Salesforce Apex Programming

We have seen what a map collection is and how to declare it. Now, we will see methods used in map manipulation in Salesforce Apex.

Following are the methods that we can use in the Map Collection, and I will explain all methods with examples:

1. Put(Key,Value) Method in Map Collection

In Map Collection, we don’t have the add() method to insert new elements or values to the map; instead, we can use the put(key, value) method to insert new values in the map collection.

Map<Integer,String>AddMapValues= new Map<Integer,String>(); 
    AddMapValues.put (101, 'LWC');
    AddMapValues.put (102, 'Apex');
    AddMapValues.put (103, 'LWC');
    AddMapValues.put (104, 'VisualForce');
system.debug(' Values in Map collections are: ' +AddMapValues);
Put Method in Map Collection in Salesforce Apex

2. Get(Key) Method in Map Collection

The get(key) method in the map collection is used to fetch the value associated with a specific key. If the key is present in the map collection, it displays the associated value of that key; if not, it returns null.

Map<Integer,String>AddMapValues= new Map<Integer,String>{101=>'LWC', 102=>'Apex', 103=>'LWC', 101=>'VisualForce'};
system.debug(' Display value of 205: ' +AddMapValues.get(205) );
system.debug(' Display value of 103: ' +AddMapValues.get(103) );
Salesforce Apex get method in Map Collection

3. ContainsKey(key) Method in Map Collection

The containsKey(key) method is used to check if a map contains a specific key. It returns true if the key is present in the map and false if not. This method is useful when you want to know if a specific key exists in the map before trying to retrieve its value. It ensures that you don’t get issues while trying to retrieve a value for a key that does not exist.

 Map<Integer,String>AddMapValues= new Map<Integer,String>(); 

    AddMapValues.put (101, 'LWC');
    AddMapValues.put (102, 'Apex');
    AddMapValues.put (103, 'LWC');
    AddMapValues.put (104, 'VisualForce');

Boolean b = AddMapValues.containsKey(102);
Boolean b1 = AddMapValues.containsKey(105);

system.debug( ' Is 102 key present in Map collection: ' +b);
system.debug( ' Is 105 key present in Map collection: ' +b1);
containsKey method in Map Collection in Salesforce Apex

4. keySet() Method in Map Collection

The keySet() method is used to retrieve all the keys from a map and store them in a set collection. The keys are stored in a set because a set has a property to store unique values. This is useful for iterating over keys or performing operations based on the keys. The returned set contains all the unique keys from the map, allowing you to access each key without worrying about duplicates.

Map<Integer,String>AddMapValues= new Map<Integer,String>(); 
    AddMapValues.put (101, 'LWC');
    AddMapValues.put (102, 'Apex');
    AddMapValues.put (103, 'LWC');
    AddMapValues.put (104, 'VisualForce');

set<Integer> MapKeys = new set<Integer>();
MapKeys = AddMapValues.keySet();

system.debug(' Display all keys from Map Collection: ' +MapKeys);
keySet method in map collection in Salesforce Apex

5. putAll(fromMap) Method in Map Collection

The putAll(fromMap) method inserts all key-value pairs from one map collection into another. If a key from the source map (fromMap) already exists in the target map, its value is modified to match that of the source map. This approach is useful for combining data from multiple maps or updating one map with information from another.

In the code below, I declared two map collections, and in both maps, I added the same key with different values. As we add MapValues2 to MapValues1, the key value of the source map gets assigned to the key of the targeted map.

Map<Integer,String> MapValues1 = new Map<Integer,String>(); 
    MapValues1.put(101,'LWC');
    MapValues1.put(102,'Apex');
    MapValues1.put(103,'LWC');
    MapValues1.put(104,'VisualForce');

Map<Integer,String> MapValues2 = new Map<Integer,String>{1001=>'Java', 1002=>'JavaScript', 1003=>'React', 104=>'HTML'}; 

MapValues1.putAll(MapValues2);
system.debug(' Display targeted map collection: ' +MapValues1);

As we execute the above code, you can see all key values from MapValues2 (source map) get added to MapValues1(target map), and the value of the same key from the target map also gets changed.

putAll method from Map Collection in Salesforce Apex

6. getSObjectType() Method in Map Collection

The getSObjectType() method is used to retrieve the Salesforce object type of the records stored in a map. This method is particularly useful when working with maps that contain Salesforce records (sObjects), as it allows us to determine the type of sObject the map is handling. It helps ensure that you work with the correct type of records in your Apex code.

In the Apex code below, we first declared the map ID and account data types. Then, using Schema.SObjectType we retrieve the SObjectType for the Account object, and accMap .getSObjectType is a way to reference the metadata about the account object.

As you execute the code below, you will get the object type.

Map<Id, Account> accMap = new Map<Id, Account>();
Schema.SObjectType objectType = accMap .getSObjectType();
System.debug('The Object Type of this Map Collection is: ' +objectType);
Salesforce SObjects declaration

7. Values() Method in Map Collection

The values() method retrieves all the values from a map as a list. This is useful when you need to access just the values of a map without concern for the keys. The returned list contains all the values from the map in no particular order. This method helps iterate over the values or perform operations on them.

Map<Integer,String>AddMapValues= new Map<Integer,String>(); 
    AddMapValues.put (101, 'LWC');
    AddMapValues.put (102, 'Apex');
    AddMapValues.put (103, 'LWC');
    AddMapValues.put (104, 'VisualForce');

list<String> MapValues = new list<String>();
MapValues = AddMapValues.values();

system.debug(' Display all values from Map Collection: ' +MapValues);
Salesforce Apex Values Method in Map Collections

8. remove(key) Method in Map Collection

The remove(key) method is used to delete a key-value pair from a map based on the specified key. If the key exists in the map, its corresponding entry is removed, and the method returns the value associated with the key. If the key is not found, the method returns null.

This method is useful for removing specific entries from a map when you no longer need them or when you want to update the map’s contents.

Map<Integer,String>AddMapValues= new Map<Integer,String>(); 
    AddMapValues.put (101, 'LWC');
    AddMapValues.put (102, 'Apex');
    AddMapValues.put (103, 'LWC');
    AddMapValues.put (104, 'VisualForce');
system.debug(' Before deleting value from Map Collection: ' +AddMapValues);
AddMapValues.remove(103);
system.debug(' After deleting 103 key & value from Map Collection: ' +AddMapValues);
remove method in Salesforce Map Collection

These are the methods that we commonly use in map collection manipulation purposes using Salesforce Apex.

Conclusion

I hope you have got an idea about the map collection in Salesforce Apex. In this tutorial, I explained how to create a map collection in Salesforce Apex programming, and then I explained the syntax of some methods for manipulating the map collection with examples and their outputs.

You may like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.