-1

I have two maps with the same key now my question how to combine this into the third map?

Map<String,object> newConMap = new Map<String,object>(004 ={CONTACTID=004, [email protected], FIRST_NAME=Test TELEPHONE=129922});
 Map<String,object> newRoleMap = new Map<String,object>(004={CONTACTID=004,PROJECTNAME:Test});

Map<String,object> FinalMap = new Map<String,object>();

I need to have the following output

FinalMap :004={CONTACTID=004, [email protected], FIRST_NAME=Test TELEPHONE=129922,PROJECTNAME:Test}

please help me to resolve this merge map. Thanks in advance

2 Answers 2

1

Your question is unclear to me as to whether you have one level of map or two levels of map. The Map Class has a putAll method:

putAll(fromMap)
Copies all of the mappings from the specified map to the original map.

that will do the work for you.

If it is two levels:

Set<String> keys = new Set<String>();
keys.addAll(newConMap.keySet());
keys.addAll(newRoleMap.keySet());

for (String key : keys) {
    Map<String, Object> m1 = (Map<String, Object>) newConMap.get(key);
    Map<String, Object> m2 = (Map<String, Object>) newRoleMap.get(key);

    Map<String, Object> merged = new Map<String, Object>();
    if (m1 != null) merged.putAll(m1);
    if (m2 != null) merged.putAll(m2);

    finalMap.put(key, merged);
}
0

I am using JSON string and creating object using JSON.deserializeUntyped for making it Generic and executable in the anonymous execution. You can avoid it if object is already avalible.

Here is the code to merge two maps.

Map<String,String> newConMap = new Map<String,String>{'004' => '{"CONTACTID":"004", "EMAIL":"[email protected]", "FIRST_NAME":"Test", "TELEPHONE":"129922"}'};
Map<String,String> newRoleMap = new Map<String,String>{'004' => '{"CONTACTID":"004", "PROJECTNAME":"Test"}'};

Map<String,String> mergedMap = new Map<String,String>();

for(String newConKey : newConMap.keySet()){
    String newConDataString = (String)newConMap.get(newConKey);
    Map<String, Object> newConData = (Map<String, Object>)JSON.deserializeUntyped(newConDataString);
    String newRoleDataString = (String)newRoleMap.get(newConKey);
    Map<String, Object> newRoleData = (Map<String, Object>)JSON.deserializeUntyped(newRoleDataString);
    
    Map<String, Object> tempMap = new Map<String, Object>();
    tempMap.putAll(newConData);
    tempMap.putAll(newRoleData);
    
    mergedMap.put(newConKey, JSON.serialize(tempMap));
}

System.debug('mergedMap' + mergedMap);

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .