0

I am having data in Map which is like:

Map<string, List<string>> mapRecord = new Map<string,List<string>>();

In key I am storing the account name and in value i have List of string. i need to convert the key value from account name to account id in this map later . means i need to create a new map with same values but this time key should be account id instead of account name

Map<id, List<string>> mapRecord = new Map<id,List<string>>();

please provide any help.

0

Create new map of Account name => Id

Map<String,Id> accNametoIdMap = new <String,Id>();

put all values in accNametoIdMap when required

To copy data from 'mapRecord' to new Map of Map<Id, List<string>>, use below code

Map<Id, List<string>> mapRecordWithId = new Map<Id,List<string>>();

for(String accName: mapRecord.keySet()){
    List<String> tempList = mapRecord.get(accName);
    Id accid = accNametoIdMap.get(accName);
    mapRecordWithId.put(accid,tempList);
}
| improve this answer | |
1

Set of keys in Map is read-only, and you can't do changes to keys like mapRecord.keySet().add(something). So you can create new Map with new keys and same values.


in current case you have to match old keys (names) and new keys (ids). Lets say all account names are unique in your org, and you have already populated Map mapRecord so you can do the following:

// map to store account Name - account Id pairs
Map<String, Id> accountIdsByNameMap = new Map<String, Id>();

//query accounts to get their ids
List<Account> accounts = [
    select Id, Name
    from Account
    where Name in :mapRecord.keySet()
    ];

//fill map to get  account Id by its Name
for(Account acc :accounts){
    accountIdsByNameMap.put(acc.Name, acc.Id);
}

Map<Id, List<String>> mapRecordResult = new Map<Id,List<String>>();
//
for(String accountName :mapRecord.keySet()){
    Id accountId = accountIdsByNameMap.get(accountName);
    mapRecordResult.put(accountId, mapRecord.get(accountName));
}
| improve this answer | |
  • Thank you very much , i understand the concept now. – Atul Pandey Nov 15 '18 at 10:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.