'I have a Map<String, Account> I want to insert the account in Salesforce and Create a new Map<String,accId>
Thank you very much for helping.
Problem Statement
I have a Map containing Map a string key and Salesforce Account, I want to insert the Account but for each account, I want to create a new Map with the same string as key and Account Id as value.
Tried
What actually I did I iterate over the map get the value to insert into database and then if the record is successfully inserted I add value to the new map, "I am inserting the account in the For Loop which is a bad Practice may hit DML Limit"
Sudo Code
Account acc = new Account(Name ='Test');
Map<String,Id> accMapId = new Map<String,Id>();
Map<String,Account> accMap = new Map<String,Account>();
accMap.put('A13',acc);
for(String accIterate : accMap.keySet()){
Database.SaveResult rt = Database.insert(accMap.get(accIterate));
if(rt.isSuccess()){
accMapId.put(accIterate,rt.id);
}
}
Question: How can I avoid to insert the Account Object within for Loop and Build my accMapId
Solution 1:[1]
Use myMap.values() to "flatten" the map into a List (in your case list of accounts), insert the whole list. Such flattening just keeps references so the original accounts in the map will be silently updated with the generated record Id.
Map<String, Account> accounts = new Map<String, Account>{
'A13' => new Account(Name ='Test'),
'B14' => new Account(Name = 'Another')
};
insert accounts.values(); // You can use Database.insert() if you want, it accepts a list too.
Map<String, Id> idsByKey = new Map<String, Id>();
for(String s : accounts.keyset()){
idsByKey.put(s, accounts.get(s).Id);
}
System.debug(idsByKey);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | eyescream |
