function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
hramanihramani 

Map variable help

List<String> mergeFields = new List<String>{'Contact.AccountId','Contact.Name','Application__c.Name','Application__c.Contact__c'};
List<string> objectNames = new List<string>{'Contact','Application__c'};

I have a two list of strings. I want to use a Map variable to assign key value pairs. for objectNames key is Contact, values should contain Contact.AccountId','Contact.Name and for objectNames key is Application__c, values should contain Application__c.Name','Application__c.Contact__c
In reality , the mergefields and objectnames could be anything related to eachother not only Contact and Application__c

Map <string,List<String>> objectMap = new Map <string,List<String>>();

Please help on assigning a key value pair
pconpcon
If you know that they will always have a period in them, you could do the following
 
List<String> mergeFields = new List<String> {
    'Contact.AccountId',
    'Contact.Name',
    'Application__c.Name',
    'Application__c.Contact__c'
};  

Map<String, List<String>> objectMap = new Map<String, List<String>>();
for (String field : mergeFields) {
    String objName = field.split('.').get(0);

    if (!objectMap.containsKey(objName)) {
        objectMap.put(objName, new List<String>());
    }

    objectMap.get(objName).add(field);
}

NOTE: This code has not been tested and may contain typographical or logical errors
NOTE: When adding code please use the "Add a code sample" button (icon <>) to increase readability and make it easier to reference.