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
Priyesh Misquith 12Priyesh Misquith 12 

combining multiple map into one

<id,Sobject> map1 = <id, Sobject>();
<id,Sobject> map2 = <id, Sobject>();

if map1 and map2 contain same key with different values.
how to add map2 values to map1 without deleting map1 values.
Best Answer chosen by Priyesh Misquith 12
Dushyant SonwarDushyant Sonwar

For adding both map values , combining into single map

  1.  First loop through first map
  2. Add all element of first map
  3. check if key exist in second map , if exist add second map element in first map loop
  4. loop thrugh second map and add those element which are not in first map.

Finally you will get a joint map
 
Map <Id,Account> firstMap = new Map <Id,Account>();
Map <Id,Account> secondMap = new Map <Id,Account>();

Map<Id , list<Account>> mainMap = new Map<Id , list<Account>>();

Set<String> setOfIdsInFirstMap = new Set<String>();
for(String key : firstMap.keyset() ){
	list<Account> lstAccount = new list<Account>();
	if(secondMap.containsKey(key)){
     	lstAccount.add(secondMap.get(key));
	}
	setOfIdsInFirstMap.add(key);
	lstAccount.add(firstMap.get(key));

	mainMap.put(key)
}

for(String key : secondMap.keyset()){

	if(!setOfIdsInFirstMap.contains(key)){
		mainMap.put(key , new list<Account>{secondMap.get(key)});
	}
}

system.debug(mainMap + ' @@@@ Main Map @@@@ ');

All Answers

Dushyant SonwarDushyant Sonwar

For adding both map values , combining into single map

  1.  First loop through first map
  2. Add all element of first map
  3. check if key exist in second map , if exist add second map element in first map loop
  4. loop thrugh second map and add those element which are not in first map.

Finally you will get a joint map
 
Map <Id,Account> firstMap = new Map <Id,Account>();
Map <Id,Account> secondMap = new Map <Id,Account>();

Map<Id , list<Account>> mainMap = new Map<Id , list<Account>>();

Set<String> setOfIdsInFirstMap = new Set<String>();
for(String key : firstMap.keyset() ){
	list<Account> lstAccount = new list<Account>();
	if(secondMap.containsKey(key)){
     	lstAccount.add(secondMap.get(key));
	}
	setOfIdsInFirstMap.add(key);
	lstAccount.add(firstMap.get(key));

	mainMap.put(key)
}

for(String key : secondMap.keyset()){

	if(!setOfIdsInFirstMap.contains(key)){
		mainMap.put(key , new list<Account>{secondMap.get(key)});
	}
}

system.debug(mainMap + ' @@@@ Main Map @@@@ ');
This was selected as the best answer
Priyesh Misquith 12Priyesh Misquith 12
Hi Dushyant

I am getting following error while trying your code
Method does not exist or incorrect signature: void put(String) from the type Map<Id,List<SObject>>
Dushyant SonwarDushyant Sonwar

replace this line 
 mainMap.put(key)

to

 mainMap.put(key , lstAccount);
Priyesh Misquith 12Priyesh Misquith 12
Thank you Dushyant. It was great help.